如何运行一个带有工作簿名称的宏?

时间:2016-01-20 16:36:36

标签: excel excel-vba vba

我想运行一个宏,在其中我指定了我想要使用的工作簿的名称。

工作簿的名称更改为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
.
.
.

2 个答案:

答案 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."

然后在代码中使用wbDatawbSalary来引用该工作簿

答案 1 :(得分:2)

此代码适用于名称以DataSalary开头的所有已打开的工作簿:

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

如果您要使用名称中包含DataSalary的所有已打开工作簿,请将"Data*""Salary*"更改为"*Data*"和{{1 }}