我试图让循环函数引用一系列单元格,而不是单独输入工作表名称。
我的代码有效:
Sub LoopTest()
'
' Macro4 Macro
'
'
' Loop Test
Dim SheetsArray As Variant
Dim i As Integer
SheetsArray = Array("Bun1", "Bun2")
For i = LBound(SheetsArray) To UBound(SheetsArray)
With Worksheets(SheetsArray(i)).Select
Range("A2:G60").Select
Selection.ClearContents
End With
Next i
End Sub
但是,当我尝试将其引用到范围时,此代码不会出现:
Sub LoopTest()
'
'
' Loop Test
Dim Arr As Variant
Dim i As Integer
Dim rng As Range
Set rng = Worksheets("Names").Range("A2:A3")
Arr = rng
For i = LBound(Arr) To UBound(Arr)
With Worksheets(Arr(i)).Select
Range("A2:G60").Select
Selection.ClearContents
End With
Next i
End Sub
我得到"下标超出范围"我尝试使用它时出错,但工作表都存在(范围与第一个代码的名称相同)。调试突出显示
WIth Worksheets(Arr(i)).Select
线。任何帮助将不胜感激!
-Cr1kk0
答案 0 :(得分:2)
在为变量指定范围时,始终会获得二维数组,因此您需要指定两个维。这里也没有必要选择任何东西:
For i = LBound(Arr, 1) To UBound(Arr, 1)
Worksheets(Arr(i, 1)).Range("A2:G60").ClearContents
Next i