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 = 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 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

R3uK's user avatar
R3uK
14.6k8 gold badges49 silver badges81 bronze badges
askedOct 28, 2015 at 7:31
SINORA's user avatar
1
  • File > Options > Trust Center Click on Trust Center Settings... button Macro Settings > Check Enable all macrosCommentedOct 29, 2015 at 19:28

2 Answers2

5

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()
answeredOct 29, 2015 at 21:19
ASH's user avatar
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".

answeredNov 30, 2016 at 19:53
Hanni's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.