I need to run an Excel macro via python and I always get the following error :
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)In Excel, it is giving the following error :
Run-time error 1004: Cannot run the macro ". The macro may not be available in this workbook or all macros may be disabled.
My code is the following :
xl=win32.Dispatch("Excel.Application")wb=xl.Workbooks.Open(Filename="Path+MyExcelFile.xlsm", ReadOnly=1)xl.Visible = Truetime.sleep(1)ws=wb.Worksheets("Sheet1")ws.Cells(4,2).Value='Value1'ws.Cells(5,2).Value='Value2'ws.Cells(1,8).Value='Bool'time.sleep(10)xl.Application.Run("MyExcelFile.xlsm!macroname")result = ws.Cells(3,10).Valueprint resultxl.Application.Quit()del xlI enabled all macros through Macros security, and the macro is not defined for a specific sheet. And of course the macro is working correctly if I run it manually in Excel
- File > Options > Trust Center Click on Trust Center Settings... button Macro Settings > Check Enable all macrosASH– ASH2015-10-29 19:28:32 +00:00CommentedOct 29, 2015 at 19:28
2 Answers2
This worked fine for me. Just change the path and the name of the Macro.
from __future__ import print_functionimport unittestimport os.pathimport win32com.clientclass ExcelMacro(unittest.TestCase): def test_excel_macro(self): try: xlApp = win32com.client.DispatchEx('Excel.Application') xlsPath = os.path.expanduser('C:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.xlsb') wb = xlApp.Workbooks.Open(Filename=xlsPath) xlApp.Run('Macro1') wb.Save() xlApp.Quit() print("Macro ran successfully!") except: print("Error found while running the excel macro!") xlApp.Quit()if __name__ == "__main__": unittest.main()Comments
I tried xl.Application.Run("macroname"), then it worked. I only have one workbook opened and one unique "macroname".
Comments
Explore related questions
See similar questions with these tags.

