我想运行一个宏,在其中我指定了我想要使用的工作簿的名称。
工作簿的名称更改为Data (1), Data (2), Data (3) …
,因为我可能会打开同一个文件超过1次。对于工作簿Salary也会出现同样的情况,有时它显示为Salary (1), Salary (2)…
,并且给出了“下标超出范围”的错误。
如何运行带有工作簿名称的宏
数据,数据(1),数据(2)......和薪水,薪水(1),薪水(2)......
For i = 1 to 100
If Workbooks(“Data”).Worksheets(“Shee1).Cells(i,4).Value = 100 Then
.
.
.
For i = 1 to 100
If Workbooks(“Salary). ”).Worksheets(“Shee1).Cells(i,4).Value < 2000 Then
.
.
.
答案 0 :(得分:3)
遍历工作簿集合:
Dim wb As Excel.Workbook
Dim wbSalary As Excel.Workbook
Dim wbData As Excel.Workbook
For Each wb In Workbooks
If wb.Name Like "Data*" Then
Set wbData = wb
Else If wb.Name Like "Salary*" Then
Set wbSalary = wb
End If
Next
'// For example...
MsgBox wbData.Name & " contains " & wbData.Sheets.Count & " worksheets."
MsgBox wbSalary.Name & " contains " & wbSalary.Sheets.Count & " worksheets."
然后在代码中使用wbData
和wbSalary
来引用该工作簿
答案 1 :(得分:2)
此代码适用于名称以Data
或Salary
开头的所有已打开的工作簿:
Sub Test()
Dim Wb As Workbook
Dim i As Long
For Each Wb In Workbooks
If Wb.Name Like "Data*" Then
For i = 1 To 100
If Wb.Worksheets("Shee1").Cells(i, 4).Value = 100 Then
'....
'....
End If
Next
ElseIf Wb.Name Like "Salary*" Then
For i = 1 To 100
If Wb.Worksheets("Shee1").Cells(i, 4).Value < 2000 Then
'....
'....
End If
Next
End If
Next
End Sub
如果您要使用名称中包含Data
或Salary
的所有已打开工作簿,请将"Data*"
和"Salary*"
更改为"*Data*"
和{{1 }}