我想用Python脚本在Excel文件中运行宏。在
import os
import win32com.client
if os.path.exists(""C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm"):
xl = win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm")
xl.Visible = True
xl.Run('Mem_Leak')
脚本在打开Excel文件后失败,并给出以下错误:
C:\Users\siddharth.mungekar\AppData\Local\Programs\Python\Python36\python.exe C:/Users/siddharth.mungekar/PycharmProjects/MacroViaPython/ExcelMacroEnabler.py Traceback (most recent call last): File "C:/Users/siddharth.mungekar/PycharmProjects/MacroViaPython/ExcelMacroEnabler.py", line 14, in xl.Run('Mem_Leak') File "", line 14, in Run File "C:\Users\siddharth.mungekar\AppData\Local\Programs\Python\Python36\lib\site-packages\win32com\client\dynamic.py", line 287, in ApplyTypes result = self.oleobj.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Cannot run the macro 'Mem_Leak'. The macro may not be available in this workbook or all macros may be disabled.", 'xlmain11.chm', 0, -2146827284), None)
我试着修改信任中心的设置。在
当另一个Excel文件已经被手动打开时,该代码可以工作。在
我试着打开一个虚拟的Excel文件,然后打开目标Excel文件并运行宏。这没用。必须手动打开虚拟excel文件。在
我通过将宏放入新模块而不是“ThisWorkbook”中并调用:
完整代码:
^{pr2}$您可以尝试更新注册表中的宏设置以允许所有宏运行。您需要以管理员身份运行Python脚本,或者确保注册表项具有适当的权限:
注意,您可能需要根据安装的Office版本调整注册表路径,请使用REGEDIT进行检查。i、 e.确保
Office\14.0
存在。在另请查看Microsoft Project – how to control Macro Settings using registry keys以获取更多信息。在
相关问题 更多 >
编程相关推荐