将WKS设置为一个variables表CodeName
我有4个表单代号:
Summary Credit Debit Comments
我想执行循环设置WKS = codename,但它不工作,因为我认为当我设置数组元素我使用的引号,使得它更像一个string比表单?
码:
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
任何提示的语法?
您需要将数组设置为工作表,然后设置每个variables。 并没有引号
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
这对我来说是一个变种
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
或者,您可以通过直接引用它来设置工作表名称。 用你的第一个例子:
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
如果您需要遍历工作簿中的所有工作表,则可以在不使用数组的情况下使用它们,并将其名称用作variables,因为它可能在稍后阶段进行更改:
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