以编程方式closuresMsgBox

我在Excel文件中有一个主macros,“文件A”打开另一个Excel文件“文件B”。 打开时,加载项将数据导入到“文件B”中。 一旦插件完成导入,我想closures“文件B”,我正在寻找最好的方法来做到这一点。

我写了代码打开“文件B”(它会自动触发加载项)并closures文件,但是当加载完成后,它会打开一个MsgBox来通知用户。 我试图完全自动化一个内部过程,所以消除MsgBox编程将是理想的。

是否有可能通过VBA解雇MsgBox? 我知道,我可以在VBA中创build定时MsgBoxes,但我不创build此MsgBox(加载项是); 我只是想解雇它。 我打开创build一个Word文件,并根据需要调用macros,但不希望使用SendKeys。

由于“加载项”和Excel / VBA在同一个上下文中运行,因此每个VBA应用程序都是一个单线程的进程 ,所以我们无法启动它并在相同的 VBA应用程序中监视它的消息框。 幸运的是,有一个解决scheme可以利用不同的VBA应用程序在不同的上下文中运行的事实,所以它们可以并行运行。

我build议的解决scheme是创build一个专门用于监视和closures该消息框的MS-Word文档。 我们在Word(或任何其他办公应用程序)中需要这样做,以便使监视代码和插件的代码在不同的上下文中并行运行。

1-创build一个名为mboxKiller.docm的Wordmacros启用文档并将其放置在某个文件夹中; 即我的例子中的C:\SO 。 将此代码放在ThisDocument并保存:

 Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long Public Sub WaitAndKillWindow() On Error Resume Next Dim h As Long: h = FindWindow(vbNullString, "Microsoft Excel") If h <> 0 Then SendMessage h, 16, 0, 0 ' <-- WM_Close Application.OnTime Now + TimeSerial(0, 0, 1), "WaitAndKillWindow" End Sub Private Sub Document_Open() WaitAndKillWindow End Sub 

2-在Excel工作簿的VBA中,创build一个名为mboxKiller的类模块,其代码如下:

 Private killerDoc As Object Private Sub Class_Initialize() On Error Resume Next Set killerDoc = CreateObject("Word.Application").Documents.Open(Filename:="C:\SO\mboxKiller.docm", ReadOnly:=True) If Err.Number <> 0 Then If Not killerDoc Is Nothing Then killerDoc.Close False Set killerDoc = Nothing MsgBox "could not lauch The mboxKiller killer. The message-box shall be closed manuallt by the user." End If End Sub Private Sub Class_Terminate() On Error Resume Next If Not killerDoc Is Nothing Then killerDoc.Application.Quit False End Sub 

3-testing和使用。 在一个普通的类模块中,放置下面的代码并testing过程

 Sub Test() ' <-- run this for testing after finishing the setup Dim killer: Set killer = New mboxKiller simulateAddin simulateAddin simulateAddin End Sub ' Procedure supposed to do some calculation then display a message box Private Sub simulateAddin() Dim i As Long For i = 0 To 1000: DoEvents: Next ' simulates some calculations MsgBox "This is a message box to simulate the message box of the addin." & VbCrLf & _ "It will be automatically closed by the Word app mboxKiller" End Sub