I want to run a macro in an Excel file using a Python script.
import os
import win32com.client
if os.path.exists(""C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm"):
xl = win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm")
xl.Visible = True
xl.Run('Mem_Leak')
The script fails after opening an Excel file and gives the following error:
C:\Users\siddharth.mungekar\AppData\Local\Programs\Python\Python36\python.exe C:/Users/siddharth.mungekar/PycharmProjects/MacroViaPython/ExcelMacroEnabler.py Traceback (most recent call last): File "C:/Users/siddharth.mungekar/PycharmProjects/MacroViaPython/ExcelMacroEnabler.py", line 14, in xl.Run('Mem_Leak') File "", line 14, in Run File "C:\Users\siddharth.mungekar\AppData\Local\Programs\Python\Python36\lib\site-packages\win32com\client\dynamic.py", line 287, in ApplyTypes result = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'Mem_Leak'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
I tried modifying the Trust Centre setting.
The code works when another Excel file has already been manually opened.
I tried opening a dummy Excel file and then opening the target Excel file and running the macro. This did not work. The dummy excel file has to be opened manually.