Excel 激活其他工作簿以运行宏

Excel 激活其他工作簿以运行宏,excel,Excel,我使用另一工作簿中的活动工作表在工作簿中创建了宏。我现在想运行我的宏,但使用另一个不同的活动工作簿来获取数据 这行代码在我的宏中出现了20次 WindowsIFS\u round\u 1.激活 …因此,我不希望在每次打开新工作簿以运行宏时更改它,例如,IFS_round_2。是否可以添加一些内容,以便宏只使用我打开的活动工作簿 谢谢 创建一个引用工作簿的变量。例如: Sub Macro1() Dim wb as Workbook Set wb = ActiveWorkbook

我使用另一工作簿中的活动工作表在工作簿中创建了宏。我现在想运行我的宏,但使用另一个不同的活动工作簿来获取数据

这行代码在我的宏中出现了20次

WindowsIFS\u round\u 1.激活

…因此,我不希望在每次打开新工作簿以运行宏时更改它,例如,IFS_round_2。是否可以添加一些内容,以便宏只使用我打开的活动工作簿


谢谢

创建一个引用工作簿的变量。例如:

Sub Macro1()
    Dim wb as Workbook
    Set wb = ActiveWorkbook

    wb.Activate

    'DO CODE HERE
End Sub

这有帮助吗?

我不知道您是否以编程方式打开另一个工作簿,但此解决方案有效。基本上,只要打开另一个工作簿,就可以将句柄保存到该工作簿

sother_filename = "IFS_round_1"
'saves the name of the current workbook
curr_workbook = ActiveWorkbook.Name
'opens the new workbook, this automatically returns the handle to the other
'workbook (if it opened it successfully)
other_workbook = OpenWorkbook(sother_filename)
但这有什么意思?另外一个解决方案是,当只有两个工作簿打开时,自动获取工作簿名称,然后使用该名称调用另一个工作簿

Function GetOtherWBName()
    GetOtherWBName = ""

    'if we dont have exactly two books open
    'we don't know what to do, so just quit
    If (Workbooks.Count) <> 2 Then
        Exit Function
    End If

    curr_wb = ActiveWorkbook.Name

    'if the active workbook has the same name as workbook 1
    If (StrComp(curr_wb, Workbooks(1).Name) = 0) Then
        'then the other workbook is workbook 2
        GetOtherWBName = Workbooks(2).Name
    Else
        'then this is the other workbook
        GetOtherWBName = Workbooks(1).Name
    End If

End Function
Sub ButtonClick()
    'first we save the current book, so we can call it easily later
    curr_wb = ActiveWorkbook.Name

    other_wb = GetOtherWBName()

    If Len(other_wb) = 0 Then
        MsgBox ("unable to get other wb")
        Exit Sub
    End If

    'now to call the other workbook just use
    Workbooks(other_wb).Activate

    'all the rest of your code
End Sub