如何将循环计数器值添加为数组名称后缀

时间:2017-01-27 19:21:04

标签: excel vba

我有3个变体数组: 数组1 ARRAY2 ARRAY3

我想将my循环的计数器值添加到数组名称的末尾,以保存重复相同的代码行。 :

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

而不是:

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

我尝试过使用:

  • 阵列&我
  • 阵列& CSTR(ⅰ)
  • 阵列(I)

是否可以将计数器值附加为后缀以完成数组名称?

2 个答案:

答案 0 :(得分:1)

这应该有效:

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

由于Array()返回一个基于0的数组,因此需要注意索引。

答案 1 :(得分:0)

您是否可以尝试将所有三个数组存储在数组中,然后使用i引用包含的数组?例如,

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

所以在你的情况下,你会有

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.