Search code examples
c#.netinteropoffice-interopexcel-interop

detect/close excel message box via C# after macro invokation


I can invoke a VBA/Excel macro via C#. If the user (in my case a C# program) entered invalid values a message box appears. This is no problem as I can time out via C# and make a decision based on that (i.e. determine whether a message box appears). The problem is that excel does not close properly when a message box appears. I am using this code to close excel:

excelApp.DisplayAlerts = false;
Marshal.FinalReleaseComObject(someSheet);
excelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(excelWorkbook);
GC.Collect();
GC.WaitForPendingFinalizers();

Everything closes but excel and the message box stay open. I there a way to close the message box from c#?


Solution

  • I have successfully used the Microsoft solution for an office automation software that i implemented. It is not elegant and it comes with prerequisites (the message box should be holding the focus and there has to be no user interaction while the automation is running), but it works - click the box away with the SendKeys method!