Python运行Excel宏

3

我正在尝试使用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") 去掉,我的脚本可以正常打开和关闭。 当我运行这个命令时,我会收到以下错误:

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)

我已经启用了宏并且知道它在工作簿中,问题出在哪里?


1
你尝试过减少调用次数吗?例如 xl.run("WorkingFull") - SeanC
请确保您的宏不是私有的。另外尝试使用 xl.run(wb.WorkingFull),看看是否有效。 - KFleschner
工作了,但我遇到了错误,但似乎运行了我的宏。我知道这唯一的原因是我的宏保存了一个文件。回溯(最近的调用最后):文件“C:\Python27\file1.py”,第6行,在<module>中,xl.run(“WorkingFull”)文件“<COMObject Excel.Application>”,第2行,运行com_error:“(-2147352567,“发生异常。”,(0,无,无,无,0,-2146788248),无)” - Trying_hard
1个回答

5
请见下面的代码,用于使用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()

3
虽然这个链接可能回答了问题,但最好在这里包含答案的基本部分,并提供链接以供参考。仅有链接的答案如果链接页面发生更改可能会变得无效。 - Uyghur Lives Matter
1
cpBurnz - 我理解你的担忧,我已经放置了上面的代码,它将展示给用户如何使用Python运行Excel宏。如果你能友好地投票支持我的答案,我将非常感激。 - Developer
1
那看起来好多了。 - Uyghur Lives Matter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接