Home > Software engineering >  Loop on multiple arrays in an array
Loop on multiple arrays in an array

Time:05-31

I have multiple arrays that I need to print on a sheet. my idea was like:

tables = array("table1","table2",....)
for z= lbound(tables,1)to ubound(tableaux,1)
for j= lbound(tables(z),1)to ubound(tables(z),1)
for k= lbound(tables(z),2)to ubound(tables(z),2)

msg tables(z)(j,k)
next
next
next

is there a way to do that? otherwise i will need to recopy and reuse same code for each table.

thanks in advance

CodePudding user response:

Please, try the next adapted code:

Sub LoopInTablesArrays()
   Dim tables, tbl1 As ListObject, tbl2 As ListObject, table1, table2
   Dim z As Long, j As Long, k As Long
   
   Set tbl1 = ActiveSheet.ListObjects("Table23") 'use here an existing table sheet/name
   Set tbl2 = ActiveSheet.ListObjects("Table26") 'set an existing table
   
   table1 = tbl1.Range.value  'place the table range in an array
   table2 = tbl2.Range.value  'place the table range in an array
   tables = Array(table1, table2) 'you may place here as many arrays as you need

   For z = LBound(tables, 1) To UBound(tables, 1)
        For j = LBound(tables(z), 1) To UBound(tables(z), 1)
            For k = LBound(tables(z), 2) To UBound(tables(z), 2)
                Debug.Print tables(z)(j, k)
            Next k
        Next j
   Next z
End Sub

It returns in Immediate Window. Sending a lot of messages may be annoying...

To see Immediate Window, press Ctrl G, being in VBE.

  • Related