I have multiple Excel instances running and want to connect to a particular file that is open in one of them. I tried following the instructions by Tim Golden to get the workbook by its full filename. This is what I did in iPython:
import win32com.client as win32
xl1 = win32.Dispatch("Excel.Application")
xl1.Visible = False
wb1 = xl1.Workbooks.Add()
wb1.SaveAs(r"C:\Users\[...]\test.xlsx")
xl2 = win32.DispatchEx("Excel.Application")
wb2 = win32.GetObject(r"C:\Users\[...]]\test.xlsm")
The result is:
Traceback (most recent call last)
<ipython-input-22-471d068eb257> in <module>
----> 1 wb2 = win32.GetObject(r"C:\Users\[...]\test.xlsm")
c:\users\[...]\venv\lib\site-packages\win32com\client\__init__.py in GetObject(Pathname, Class, clsctx)
70 return GetActiveObject(Class, clsctx)
71 else:
---> 72 return Moniker(Pathname, clsctx)
73
74 def GetActiveObject(Class, clsctx = pythoncom.CLSCTX_ALL):
c:\users\[...]\venv\lib\site-packages\win32com\client\__init__.py in Moniker(Pathname, clsctx)
85 Python friendly version of GetObject's moniker functionality.
86 """
---> 87 moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
88 dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
89 return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
com_error: (-2147221014, 'Moniker cannot open file', None, None)
What am I doing wrong?