Python:使用Python运行Excel宏

3

我需要通过Python运行Excel宏,但总是出现以下错误:

result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)

在 Excel 中,出现以下错误:
运行时错误 1004: 无法运行宏“”。该宏可能在此工作簿中不可用,或所有宏都已禁用。
我的代码如下:
xl=win32.Dispatch("Excel.Application")
wb=xl.Workbooks.Open(Filename="Path+MyExcelFile.xlsm", ReadOnly=1)
xl.Visible = True
time.sleep(1)
ws=wb.Worksheets("Sheet1")
ws.Cells(4,2).Value='Value1'
ws.Cells(5,2).Value='Value2'
ws.Cells(1,8).Value='Bool'
time.sleep(10)
xl.Application.Run("MyExcelFile.xlsm!macroname")
result = ws.Cells(3,10).Value
print result
xl.Application.Quit()
del xl

我已通过宏安全性启用了所有宏,但该宏未针对特定工作表定义。当然,如果我在Excel中手动运行它,则该宏可以正常工作。


文件 > 选项 > 信任中心 点击“信任中心设置”按钮 宏设置 > 选中启用所有宏 - ASH
2个回答

5

这对我来说很有效。只需更改路径和宏的名称即可。

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:\\Users\\rshuell001\\Desktop\\Valuation Code Rollover.xlsb')
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('Macro1')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()

-1

我尝试了 xl.Application.Run("macroname"),然后它起作用了。我只打开了一个工作簿和一个唯一的 "macroname"。


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