我们假设我有两个不同的文件:" 1"和" a1"。 我想用" 1"中的宏打开第二个。然后从" a1"
运行代码所以,在" 1"我有以下代码:
Sub anotherMacro()
Dim path As String
Dim Fname As String
Dim macroName As String
path = ActiveWorkbook.path
Fname = ActiveWorkbook.Name
Workbooks.Open (path & "\a" & Fname)
Application.Run "a1.xlsm!Module1.SecondMacro"
MsgBox "Am I still here?"
End Sub
文件中的第二个宏" a1"看起来像那样:
Sub SecondMacro()
ActiveWorkbook.Close
End Sub
当我使用Application.Run命令时,msgbox没有被执行。 " a1"正在打开,关闭,然后没有进一步的行动。
有没有办法回到" 1"并显示msgbox?
答案 0 :(得分:0)
我注意到执行Workbook.Close
后,VBA停止执行。因此,您应该注意Workbook.Close之后放置的代码。
您可以考虑将Workbook.Close
方法转换为1.xlsm。在执行Workbook.Close
方法之前执行任何操作。
我修改了代码如下。
<强> 1.xlsm 强> 模块1
Option Explicit
Sub anotherMacro()
Dim path As String
Dim Fname As String
Dim macroName As String
With Application
path = .ThisWorkbook.path
Fname = .ThisWorkbook.Name
.Workbooks.Open (path & "\a" & Fname)
.Run "a1.xlsm!Module1.SecondMacro"
End With
End Sub
Sub WelcomeBack()
MsgBox "Am I still here?"
Application.ThisWorkbook.Activate
' Activate 1.xlsm. This is optional, depending on your needs.
' Add code here to perform any further actions.
Application.Workbooks("a1.xlsm").Close
' Close a1.xlsm. VBA stops here.
End Sub
<强> a1.xlsm 强> 模块1
Option Explicit
Sub SecondMacro()
' Add code here to perform any actions.
Application.Run "1.xlsm!Module1.WelcomeBack"
' Go back to 1.xlsm
End Sub
PS:查看Application.ActiveWorkbook
和Application.ThisWorkbook
之间的区别。
答案 1 :(得分:0)
如果您将VBA代码放在XLAM文件而不是XLSM文件中,则可以将其添加为Excel加载项,然后它可以同时与所有工作簿通信。