3
votes

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 = True
time.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).Value
print result
xl.Application.Quit()
del xl

I 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

2
File > Options > Trust Center Click on Trust Center Settings... button Macro Settings > Check Enable all macrosASH

2 Answers

5
votes

This worked fine for me. Just change the path and the name of the Macro.

from __future__ import print_function
import unittest
import os.path
import win32com.client

class 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()
-1
votes

I tried xl.Application.Run("macroname"), then it worked. I only have one workbook opened and one unique "macroname".