2016-08-10 47 views
0

我目前有一个创建和打开excel文件实例的宏。我正在寻找在这些新实例中运行宏。 事情是宏是巨大的,需要大量的时间来运行,这会暂停两个实例的Excel。如何在独立实例中独立运行宏而不拖延当前的Excel实例?

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

+1

只需创建一个新的“Excel.Application”实例以供它们运行。 – Comintern

回答

0

您可以创建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 
+0

感谢您的迅速回复!尽管onTime延迟,事件仍然相互结合并挂起。我也禁用了事件。 – TJYen

+0

我不确定你的意思是“事件仍然彼此相连” - 我已经用一些简单的例子测试过了,上面的修订版在任何代码在'wb'执行之前成功地打印了'Debug.Print'语句工作簿。 –

+1

感谢您的示例代码并回复!澄清我的错误。 – TJYen