Excel process won't quit after COM automation

2019-07-23 16:56发布

问题:

I need to automate a specific version of Excel (2003), independent of the default version installed on the target machine. For this purpose, I am using the following steps:

  • launch Excel by supplying the desired executable to CreateProcess
  • find the main and accessible window with EnumWindows and EnumChildWindows
  • use AccessibleObjectFromWindow to get an object from the Excel object model
  • do the automation stuff through COM smart pointers

This all works fine, but the Excel process will not terminate after a call to Quit on the ExcelApplication object. The same setup with Word works as intended, and the process terminates as it should. Any idea about why Excel behaves differently would be much appreciated.

I've read about similar problems when automating Excel from .NET, where dangling COM references are the reason. However, if that is the reason in my C++ case as well, I don't understand why. Even if I do nothing except Quit, the process still remains alive:

/* create process, get handle to accessible Excel window */

Excel11::_ApplicationPtr excelApplication;

try
{
  Excel11::WindowPtr::Interface* pInterface;
  if ( ::AccessibleObjectFromWindow( hwndExcelAccessible, OBJID_NATIVEOM, IID_IDispatch, reinterpret_cast< void** >( &pInterface ) ) == S_OK )
  {
    excelApplication = pInterface->Application;
    pInterface->Release();
  }
}
catch ( _com_error& e ) { /* omitted */ }

excelApplication->Quit();

回答1:

What you are doing is no longer supported by Microsoft: http://support.microsoft.com/kb/257757 (it talks about server-side code, but it references any non-interactive solutions regardless of architecture).

That notwithstanding, I believe I ran into a similar problem in some .Net code a while back and the solution was to forcibly kill Excel when done with it. I can't remember the exact reason why that had to be done, though.