运行Excelmacros的Python

我想用python来运行一个excelmacros,然后closuresexcel。 我有以下几点:

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 

我的脚本将打开并closures罚款,如果我拿出xl.run(“File1.xlsm!WorkingFull”)当我运行这个我得到以下错误:

Traceback(最近一次调用的最后一个):在文件“C:\ Python27 \ File1.py”,第6行,在xl.run(“File1.xlsm!WorkingFull”)中,第2行,在运行com_error:(-2147352567 ,'Exception occurred。',(0,u'Microsoft Excel',u“无法运行macros'File1.xlsm!WorkingFull'。macros可能在此工作簿中不可用或者所有macros可能被禁用。 xlmain11.chm',0,-2146827284),无)

我有macros启用,我知道它在工作簿,是什么问题?

请参阅下面的代码使用python运行Excelmacros。 你可以在这个网站 – 链接find这个代码。 使用本网站的其他参考为Excel,VBA和Python脚本,这可能会在未来有所帮助。

 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()