2016-08-10 48 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