如何在不停止当前 excel 实例的情况下在单独的实例中独立地 运行 宏?

How to Run macro independently in seperate instance without stalling current excel instance?

我目前有一个宏可以创建和打开 excel 个文件的实例。我正在寻找这些新实例中的 运行 宏。 问题是宏很大,运行 需要相当长的时间,这会暂停 excel 的两个实例。

有没有办法在那个特定 excel 应用程序的 vbeditor 中 运行 另一个实例的宏? 这样,当前宏可以在另一个实例 运行s 时继续。

您可以创建 Excel 的新实例,但您需要使用新实例的 OnTime 方法。如果您只是尝试使用 .Run 语句从当前工作簿执行它们,那将占用线程。

这是一个示例,我已经针对正常调用的过程对此进行了测试,还包括 .EnableEvents 以防止事件处理程序在第二个工作簿打开时触发。如果没有这个,事件处理程序(如果有的话)可能会在其运行期间触发和暂停执行。

Sub main()
Dim oXL As Excel.Application
Dim wb As Workbook
Dim filePath$, fileName$, moduleName$, procName$

'## The locaation of the file you want to open, which contains the macro
filePath = "C:\debug\"
'## The name of the workbook containing the macro
fileName = "book2.xlsm"
'## The name of the module containing the macro:
moduleName = "Module1"
'## The name of the macro procedure
procName = "foo"
'## Create new instance of Excel
Set oXL = New Excel.Application
oXL.Visible = True 'or True, if you prefer
'## Open the file containing the macro
oXL.EnableEvents = False
Set wb = oXL.Workbooks.Open(filePath & "\" & fileName)
oXL.EnableEvents = True
'## Use the OnTime method to hand the thread to other instance of Excel
oXL.Application.OnTime Now + TimeValue("0:00:05"), fileName & "!" & moduleName & "." & procName
'## Inform user that the macro is running in the other workbook/instance of Excel
Debug.Print "The procedure " & procName & " is running in " & fileName

wb.Activate
Set oXL = Nothing
End Sub