我是vba的新手,我正在尝试创建一个子例程,该子例程将对5个工作簿执行相同的复制和粘贴操作。
我正在尝试通过构建一个包含所有需要按以下功能执行的窗口的数组来做到这一点:
Sub Copyinforevised()
Dim i As Integer
Dim z As Integer
i = 1
z = 5
Dim wb(i To z) As Window
wb (1): Set wb1 = Windows("Chariot OPS project workbook.xlsx")
wb (2): Set wb2 = Windows("Chariot RAN project workbook.xlsx")
wb (3): Set wb3 = Windows("Chariot AT project workbook.xlsx")
wb (4): Set wb4 = Windows("Chariot OSS project workbook.xlsx")
wb (5): Set wb5 = Windows("Chariot MOB project workbook.xlsx")
For i = 1 To z
Windows(wb(i)).Activate
[function to be done to the workbook]
Next i
End Sub
但是当我尝试运行宏时,出现错误“查询编译错误常量表达式”
答案 0 :(得分:2)
这是一种有效的语法:
Sub Copyinforevised()
Dim i As Integer
Dim z As Integer
Dim wb
i = 1
z = 5
ReDim wb(i To z) As Window
Set wb(1) = Windows("Chariot OPS project workbook.xlsx")
Set wb(2) = Windows("Chariot RAN project workbook.xlsx")
Set wb(3) = Windows("Chariot AT project workbook.xlsx")
Set wb(4) = Windows("Chariot OSS project workbook.xlsx")
Set wb(5) = Windows("Chariot MOB project workbook.xlsx")
End Sub
请注意使用ReDim
。
答案 1 :(得分:0)
您无需设置一堆Workbook
变量(这肯定是这样做的一种方法),您可以将工作簿名称放入数组中,并使用它来遍历:
Sub Copyinforevised()
Dim wbList() As Variant
wbList = Array("Chariot OPS project workbook.xlsx", "Chariot RAN project workbook.xlsx", _
"Chariot AT project workbook.xlsx", "Chariot OSS project workbook.xlsx", _
"Chariot MOB project workbook.xlsx")
Dim i As Long
For i = LBound(wbList) To UBound(wbList)
With Workbooks(wbList(i))
' Do whatever with the workbook
Debug.Print .Sheets(1).Range("A1").Value
End With
Next i
End Sub
(请注意,这些工作簿必须打开。)