我有4个表格代号:
Summary
Credit
Debit
Comments
我想执行一个循环设置WKS =代号但是它不起作用因为我认为当我设置数组元素时我使用引号使它更像是字符串而不是表单?
代码:
Dim sheetArray(4) as Variant
Dim wks as Worksheet
sheetArray(1) = "Summary"
sheetArray(2) = "Credit"
sheetArray(3) = "Debit"
sheetArray(4) = "Comments"
for i = 1 to 4
set wks = sheetArray(i)
...do stuff...
next
这对我不起作用......相反,我必须这样做,感觉很难看。
代码:
for i = 1 to 4
if i = 1 then
set wks = Summary
elseif i = 2 then
....etc
有关语法的任何提示吗?
答案 0 :(得分:3)
您需要将数组设置为工作表,然后设置每个变量。没有引号
Dim sheetArray(4) as Worksheet
Dim wks as Worksheet
Set sheetArray(1) = Summary
Set sheetArray(2) = Credit
Set sheetArray(3) = Debit
Set sheetArray(4) = Comments
for i = 1 to 4
set wks = sheetArray(i)
...do stuff...
next
答案 1 :(得分:1)
这适用于我作为变体
Sub test()
Dim sheetArray() As Variant
ReDim sheetArray(1 To 3)
sheetArray(1) = "Sheet1"
sheetArray(2) = "Sheet2"
sheetArray(3) = "Sheet3"
Dim ws As Worksheet
For i = LBound(sheetArray) To UBound(sheetArray)
Set ws = ThisWorkbook.Sheets(sheetArray(i))
MsgBox (ws.Name)
Next
End Sub
答案 2 :(得分:0)
或者,您可以通过直接引用它来设置工作表名称。使用你的第一个例子:
Dim sheetArray(4) as Variant
Dim wks as Worksheet
sheetArray(1) = "Summary"
sheetArray(2) = "Credit"
sheetArray(3) = "Debit"
sheetArray(4) = "Comments"
for i = 1 to 4
wks.Name = sheetArray(i) ###This is the line I changed. Notice wks.Name
...do stuff...
next
答案 3 :(得分:0)
如果需要循环遍历工作簿中的所有工作表,可以不使用数组并将其名称用作变量,因为它可能会在以后更改:
Sub WorksheetLoop()
' Declare Current as a worksheet object variable.
Dim Current As Worksheet
' Loop through all of the worksheets in the active workbook.
For Each Current In Worksheets
' Insert your code here.
' This line displays the worksheet name in a message box.
MsgBox Current.Name
Next
End Sub