3

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

1
  • File > Options > Trust Center Click on Trust Center Settings... button Macro Settings > Check Enable all macros Commented Oct 29, 2015 at 19:28

2 Answers 2

5

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()
Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.