2
votes

I am trying to use python to run an excel macro and then close excel. I have the following:

 import win32com.client
 import os

 xl = win32com.client.DispatchEx("Excel.Application")
 wb = xl.workbooks.open("X:\Location\Location2\File1.xlsm")
 xl.run("File1.xlsm!WorkingFull")
 xl.Visible = True
 wb.Close(SaveChanges=1)
 xl.Quit

My script will Open and close fine if I take out the xl.run("File1.xlsm!WorkingFull") When I run this I get the following error:

Traceback (most recent call last): File "C:\Python27\File1.py", line 6, in xl.run("File1.xlsm!WorkingFull") File "", line 2, in run com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'File1.xlsm!WorkingFull'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)

I have macros enabled and I know its in the workbook, what is the problem?

1
have you tried reducing the call? xl.run("WorkingFull")?SeanC
Make sure your macro is not private. Also try xl.run(wb.WorkingFull) and see if that works.KFleschner
worked, but I am getting the error, but it seems to run my macro. The only reason I know this is my macro saves a file off. Traceback (most recent call last): File "C:\Python27\file1.py", line 6, in <module> xl.run("WorkingFull") File "<COMObject Excel.Application>", line 2, in run com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)Trying_hard

1 Answers

5
votes

please see below the code for running an Excel macro using python. You can find this code in this Site - Link. Use this site for other references for excel, vba and python scripts which might be helpful in the future.

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:\test1\test2\test3\test4\MacroFile.xlsm')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('macroName')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()