vba Python 运行 Excel 宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11636200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Running an Excel Macro
提问by Trying_hard
I am trying to use python to run an excel macro and then close excel. I have the following:
我正在尝试使用 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
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:
如果我取出 xl.run("File1.xlsm!WorkingFull") 我的脚本将正常打开和关闭当我运行它时,我收到以下错误:
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)
回溯(最近一次调用):文件“C:\Python27\File1.py”,第 6 行,在 xl.run("File1.xlsm!WorkingFull") 文件“”,第 2 行,在运行 com_error: (-2147352567 , '发生异常。', (0, u'Microsoft Excel', u"无法运行宏 'File1.xlsm!WorkingFull'。该宏可能在此工作簿中不可用,或者所有宏都可能被禁用。", u' xlmain11.chm', 0, -2146827284), 无)
I have macros enabled and I know its in the workbook, what is the problem?
我启用了宏并且我知道它在工作簿中,有什么问题?
回答by Developer
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.
请参阅下面使用 python 运行 Excel 宏的代码。您可以在此站点链接中找到此代码。将此站点用于 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()