【问题标题】:Close a modal opened by vba macro with c#用c#关闭由vba宏打开的模态
【发布时间】:2017-02-18 17:49:55
【问题描述】:

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

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

有什么办法可以关闭那个模态窗口吗?还是有可能??

我试过了:

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

但它不起作用。

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

最好的问候!

【问题讨论】:

标签: c# vba excel


【解决方案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();
    }
}

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2023-03-30
    • 2017-02-20
    相关资源
    最近更新 更多