Why do I get different lists of open workbooks in Excel COM based on which IDE executes the code?

前端 未结 1 1604
心在旅途
心在旅途 2021-01-14 04:38
import win32com.client as win32

excel = win32.gencache.EnsureDispatch(\'Excel.Application\')
for wb in excel.Workbooks:
    print(wb.Name)

When I

相关标签:
1条回答
  • 2021-01-14 05:16

    The reason must be that in one case, you connect to a running Excel instance while in the other one, open a new one (or connect to some other one).

    To ensure connecting to an existing instance, you can use win32com.client.GetActiveObject(<ProgID>) as per Attaching to an already running Office application from your application using GetActiveObject or BindToMoniker – .NET4Office.


    I'm not completely sure when either happens, but these are the patterns I noticed that may explain what you see:

    • If you have an Excel instance that was launched by hand before running your program, the program connects to that instance
    • If not, an excel.exe instance is spawned by the svchost.exe process hosting the DCOM process launcher service
      • This instance doesn't initially have any workbooks open
    • However, if you launch Excel by hand after that, a second instance is created. The DCOM instance takes priority.
    • An instance is not closed even after .Quit as long as there are references to it, so any further dispatches from the same process while it has references to it will get the same instance.
    • You can't connect to Excel processes running as different users (this includes with vs without elevation).

    So if you e.g. run your code from interactive console, or the IDE doesn't restart the Python process each time (unlikely but possible), you may have old existing references.

    0 讨论(0)
提交回复
热议问题