Home » excel » python – win32com dispatch Won't Find Already Open Application Instance

python – win32com dispatch Won't Find Already Open Application Instance

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am using python to parse an Excel file and am accessing the application COM using excel = Dispatch('Excel.Application') at the beginning of a restart the code will find the application object just fine and I will be able to access the active workbook.

The problem comes when I have had two instances of Excel open and I close the first. From then on every call to excel = Dispatch('Excel.Application') provides an application object that is different from the open instance of Excel. If I try excel.Visible=1 it opens a new Excel instance rather than showing the already open instance of excel. How do I get the COM object of the already open instance of Excel rather than creating a new instance?

How to&Answers:

When an application registers itself, only the first instance gets registered, until it dies and then the very next instance to register gets registered.

There’s no registration queue, so when your first instance dies, the second keeps unregistered, so any call to Excel.Application will launch a third instance and they’ll keep using it until it dies too.

In summary, the instances launched in between registered instances never get registered.

If you need to reuse an instance, you must keep a pointer to it.

That said, if you get an instance of an open Excel file, you might obtain a link to an unregistered Excel instance. For instance, if Excel 1 (registered) has workbook 1 open, and Excel 2 (unregistered) has workbook 2 open, if you ask for workbook 2, you’ll get Excel 2’s instance (e.g. through Workbook.Application).