Forum Discussion

Natasha_2012's avatar
Natasha_2012
Contributor
9 years ago

how to declare a dynamic 2 dimensional array using vbscript

Hi Community

 

Could you show me how to declare a dynamic 2 dimensional array using vbscript, please?

 

Have been searching on internet, but all the examples are all about the fixed size array, I need to know its size when declaring which I dont have in my case

 

Kind Regards

Nat

 

    • Natasha_2012's avatar
      Natasha_2012
      Contributor

      The above code is working fine for single dimensional array.

       

      My problem here is for 2 dimensional array.  I have subscript out of range error at my ReDim Preserve below

       

      Dim arrTestArraỵ()

      Set aData = DDT.CSVDriver(strFullFileName)

      Call aData.First

      intSize = 0

      Do While Not aData.EOF()

        For i = 0 to aData.ColumnCount - 1

            ReDim Preserve  arrTestArraỵ(intSize, aData.ColumnCount - 1)  -> it is error right at this line: subscript out of range

             arrTestArraỵ(intSize,i) = aqConvert.VarToStr(aData.Value(i))

        Next

        intSize = intSize + 1

        aData.Next

      Loop

      • joseph_michaud's avatar
        joseph_michaud
        Moderator

        The Preserve keyword can't be used if you change the size of any but the last dimension.  See ReDim Statement

         

        Since the number of columns is fixed, make that the unchanging dimension.  Transpose the matrix and enter a new row's worth of data down one column of the array.  For each new row of data make the array one column wider and enter the next row of date down the next column.

         

        Something like this:

         

        Sub Test
          Dim RowCount : RowCount = 3
          Dim ColumnCount
          Dim arr, row, column
          
          ColumnCount = 5
          ReDim arr(ColumnCount - 1, 0)
          
          row = 0
          Do While row < RowCount
            ReDim Preserve arr(ColumnCount - 1, row)
            For column = 0 to ColumnCount - 1
              arr(column, row) = row * 10 + column  ' new data
            Next
            row = row + 1
          Loop
        
          For row = 0 to RowCount - 1
            For column = 0 to ColumnCount - 1
              Log.Message("arr(" & row & ", " & column & ") = " & arr(column, row))
            Next
          Next
        End Sub