用c#关闭vba宏打开的模态

时间:2017-02-16 22:48:42

标签: c# excel vba excel-vba

我正在创建一个在Excel工作表中执行vba宏的c#程序。

vba宏完成执行后,会显示一个模态窗口,不允许继续执行我的程序。

有什么方法可以关闭那个模态窗口吗?或者甚至可能吗??

我试过了:

appExcel.DisplayAlerts = false;
appExcel.EnableEvents = false;

但它不起作用。

注意:我无法访问vba宏代码。

最好的问候!

1 个答案:

答案 0 :(得分:1)

这里是"轻量级"解决方案从我的回答here修改为纯粹VBA的类似问题。它使用两个Win32 API函数:FindWindowSendMessage

[DllImport("user32.dll")] static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")] static extern int SendMessage(int  hWnd, int wMsg, int wParam, int lParam);

    // This function endlessly waits for a window with the given
    //  title and when found sends it a WM_CLOSE message (16)
    public static void killMbox(Object windowTitle)
    {
        for (int h = 0; h == 0;)
        {   Thread.Sleep(1000);
            h = FindWindow(null, windowTitle.ToString());
            if (h != 0)
                SendMessage(h, 16, 0, 0);
        }
    }

    static void Main(string[] args)
    {
        Thread mboxKiller = new Thread(killMbox);
        // Excel message-boxes usually have title "Microsoft Excel".
        // Change if your message-box has a different title
        mboxKiller.Start("Microsoft Excel");

        Application xlApp = new Application();
        Workbook wb = xlApp.Workbooks.Open("C:/SO/SO.xlsm");
        xlApp.Visible = true;
        xlApp.Run("doMessageBox"); // launches a macro that displays a message box
        // now the mboxKiller will close that mbox, code here proceeds
        // ...
        xlApp.Quit();
    }
}