Search code examples
vbacatia

ReDim Preserve 3 Dimensinal array VBA


I am working on VB code in catia.There are multiple sheets and each sheet has few tables for which the rows and columns and number of tables are not fixed. I want to create a 3 dimensional array which can capture each table data into each 2 Dimensional array under it. I tried Redim and Redim preserve but its not working.

here is the code example.

table 1

1 2 3 4 5

2 3 2 3 2

1 2 1 1 4

table 2

9 8 8

7 8 6

these are sample of tables in each sheet.. Say i was able to calculate dimensions of the table and number of table in sheet.

here is the sample of code i tried.

Dim array() as variant

Dim ntables as integer 'Number of tables

Dim rcount as integer  

Dim ccount as integer

for each table in tables

rcount=table.rows.count

ccount=table.columns.count

redim preserve array(ntables,rcount,ccount) as varient

next

''' '''

i want a multi dimensional array as

array(0)

  array(0,0)

        array(0,0,1)

        array(0,0,2)

        array(0,0,3)

        array(0,0,4)

        array(0,0,5)

  array(0,1)

        array(0,1,1)

        array(0,1,2)

        array(0,1,3)

        array(0,1,4)

        array(0,1,5)

 array(0,2)

        array(0,2,1)

        array(0,2,2)

        array(0,2,3)

        array(0,2,4)

        array(0,2,5)

array(1)

  array(1,0)

        array(1,0,1)

        array(1,0,2)

        array(1,0,3)

  array(1,1)

        array(1,1,1)

        array(1,1,2)

        array(1,1,3)

Solution

  • Instead of using a 3D array consider to use a Collection of 2D arrays, if only the number of tables varies.

    Consider the following working example (using 2 tables)

    Public Sub TestFillData()
    
        Dim tables() As Variant
        tables = Array( _
            Range("A2").Resize(16, 4), _
            Range("I2").Resize(100, 7) _
            )
            
        Dim col As New Collection
        Dim item As Variant
        For Each item In tables
            col.Add item.Value2    ' Range().Value2 returns a 2D array
                                   ' when more than one cell is referenced.
        Next
        
        ' col.Count() = 2
        ' col(1) = 16x4 array
        ' col(2) = 100x7 array
    
    
    End Sub