简体   繁体   中英

How to add loop counter value as array name suffix

I have 3 variant arrays: Array1 Array2 Array3

I am wanting to add the counter value of my for loop to the end of the array name to save repeating the same code line over eg :

For i = 1 To oXlWkBk.Sheets.Count
FillArray ArraySource & i, "B1:" & oCurrentWs.Cells(lNumRows, lNumCols).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Next i

instead of:

For i = 1 To oXlWkBk.Sheets.Count
FillArray ArraySource1, "B1:" & oCurrentWs.Cells(lNumRows, lNumCols).Address(RowAbsolute:=False, ColumnAbsolute:=False)

FillArray ArraySource2, "B1:" & oCurrentWs.Cells(lNumRows, lNumCols).Address(RowAbsolute:=False, ColumnAbsolute:=False)

FillArray ArraySource3, "B1:" & oCurrentWs.Cells(lNumRows, lNumCols).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Next i

I've tried using:

  • Array & i
  • Array & Cstr(i)
  • Array(i)

Is it possible to append the counter value as a suffix to complete the array name?

This should work:

Dim Arrays As Variant
Arrays = Array(Array1, Array2, Array3)

For i = 1 To oXlWkBk.Sheets.Count
    FillArray Arrays(i-1), "B1:" & oCurrentWs.Cells(lNumRows, lNumCols).Address(RowAbsolute:=False, ColumnAbsolute:=False)
Next i

Since Array() returns a 0-based array you need to be careful with the indices.

Can you try to store all three arrays inside an array and then reference the containing array with the i ? For example,

Sub test()
largerArray = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
For i = 0 To 2
    Debug.Print (sumArray(largerArray(i)))
Next i
End Sub
Function sumArray(thisArray As Variant) As Integer
sumArray = 0
For i = LBound(thisArray) To UBound(thisArray)
    sumArray = sumArray + thisArray(i)
Next i
End Function

So in your case, you would have

largerArray=Array(ArraySource1, ArraySource2, ArraySource3)
for i=0 to oXlWkBk.Sheets.Count
    FillArray largerArray(i), "B1:" & oCurrentWs.Cells(lNumRows, lNumCols).Address(RowAbsolute:=False, ColumnAbsolute:=False)

etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM