在另一个工作簿上运行一个工作簿中的代码

问题描述 投票:0回答:1

我有两本作业簿。假设 book1 和 book2。

我书上有一个宏1。我想执行book2中的任务。

我试过了

Application.run "'workbook1.xlsm", !macro1'"

它在创建代码的工作簿中运行。

excel vba
1个回答
0
投票

首先,确保两个工作簿都已打开。然后,在包含宏的工作簿(book1)中,您可以使用以下代码来运行另一个工作簿(book2)中的宏:

Sub RunMacroInAnotherWorkbook()
    Dim wb As Workbook
    
    ' Check if the target workbook (book2) is open
    On Error Resume Next
    Set wb = Workbooks("book2.xlsx") ' Change the filename if needed
    On Error GoTo 0
    
    ' If the target workbook is open, run the macro
    If Not wb Is Nothing Then
        wb.Sheets("Sheet1").Activate ' Activate a specific sheet if needed
        Application.Run "'" & wb.Name & "'!MacroName" ' Change MacroName to the actual macro name
    Else
        MsgBox "The target workbook is not open.", vbExclamation
    End If
End Sub

将“book2.xlsx”替换为第二个工作簿的实际名称,将“MacroName”替换为您要运行的宏的名称。另外,根据需要调整工作表名称和其他详细信息。

确保您已在两个工作簿中启用宏并授予它们运行所需的权限。

© www.soinside.com 2019 - 2024. All rights reserved.