Python运行Excel宏

时间:2012-07-24 17:30:25

标签: python excel vba

我正在尝试使用python运行excel宏,然后关闭excel。我有以下内容:

 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

如果我取出xl.run(“File1.xlsm!WorkingFull”),我的脚本将打开并关闭 当我运行这个时,我收到以下错误:

追踪(最近一次通话):   文件“C:\ Python27 \ File1.py”,第6行,in     xl.run( “File1.xlsm!WorkingFull”)   文件“”,第2行,在运行中   com_error:(-2147352567,'异常发生。',(0,u'Microsoft Excel',u“无法运行宏'File1.xlsm!WorkingFull'。宏可能在此工作簿中不可用,或者所有宏都可能被禁用。,“u'xlmain11.chm',0,-2146827284),无)

我启用了宏,我知道它在工作簿中,有什么问题?

1 个答案:

答案 0 :(得分:3)

请参阅下面使用python运行Excel宏的代码。您可以在此Site - Link中找到此代码。将此站点用于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()