1

I'm creating a c# program that executes a vba macro in an excel sheet.

After the vba macro finishes its execution, it displays a modal window, that does not allow to continue with the execution of my program.

Is there any way how I can close that modal window? or is it even possible??

I have tried:

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

but it did not work.

NOTE: I do not have access to the vba macro code.

best regards!

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
Jorge G.
  • 83
  • 9
  • 1
    Possible duplicate of [Handle Alert PopUp Dialog of Macro enabled Excel File using C#](http://stackoverflow.com/questions/38588994/handle-alert-popup-dialog-of-macro-enabled-excel-file-using-c-sharp) – Comintern Feb 16 '17 at 23:46

1 Answers1

3

Here's a "lightweight" solution modified from my answer here to a similar question that was purely VBA. It uses two Win32 API functions: FindWindow and SendMessage.

[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();
    }
}
Community
  • 1
  • 1
A.S.H
  • 29,101
  • 5
  • 23
  • 50