VBA:范围参考数组

在VBA中,我试图创build一个范围引用数组。 这是我目前的尝试:

Dim columnName() As String Dim colIndex() As Long Dim colRange() As Range colCount = 10 ReDim columnName(colCount) ReDim colIndex(colCount) ReDim colRange(1 To colCount) columnName(ID) = "ID" 'etc For i = 1 To UBound(columnName) colIndex(i) = WS.Range("A1", "ZZ1").Find(columnName(i), LookIn:=xlValues, MatchCase:=False).column colRange(i) = WS.Range(Cells(2, colIndex(i)), Cells(LastRowIndex, colIndex(i))) If 1 = 1 Then 'debugging Application.ScreenUpdating = True Debug.Print colRange(i).Value Debug.Print colRange(i).Address colRange(i).Select Application.ScreenUpdating = False End If 

当我尝试在数组中存储多个引用时,我得到这样的东西:

 i = 1 colIndex(i) = 8 Cells(2, colIndex(i)) = 123 Cells(LastRowIndex, colIndex(i)) =789 colRange(i) = Nothing 

我已经尝试使colRange变体,但似乎没有任何工作。 没有解决scheme,我通过谷歌或StackOverflowfind似乎解决这个问题。

除了上面我的评论,这里是一个例子

 Sub Sample() Dim columnName() As String Dim rng As Range colCount = 10 ReDim columnName(colCount) ID = 1 columnName(ID) = "A" 'MsgBox Cells(1, columnName(1)).Address Cells(1, columnName(1)).Value = "Blah Blah" Set rng = Cells(1, columnName(1)) With rng MsgBox .Address .Value = "Something" '~~> Do whatever you want to do with that range here End With End Sub 

避免使用。select。 直接在范围上执行操作,就像我上面所做的一样。 有趣的阅​​读