Python Running an Excel Macro
Question: 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?


Answer: please see below the code for running an Excel macro using python. You can
find this code in this [Site -
Link](https://sites.google.com/site/exceldriven/selenium-webdriver/python-
scripts/run-an-excel-macro-using-python). 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()
    

