如何使用Python脚本运行Excel宏?

2024-07-01 08:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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文件。在


Tags: 文件runinpyclientlineexcelmem
2条回答

我通过将宏放入新模块而不是“ThisWorkbook”中并调用:

xl.Run("Module1.UpdateTable")

完整代码:

^{pr2}$

您可以尝试更新注册表中的宏设置以允许所有宏运行。您需要以管理员身份运行Python脚本,或者确保注册表项具有适当的权限:

import winreg
import os
import win32com.client


def registry_set_key(hive, regpath, key, type, value):
    try:
        hkey = winreg.OpenKey(hive, regpath, 0, winreg.KEY_ALL_ACCESS)
    except FileNotFountError as e:
        hkey = winreg.CreateKey(hive, regpath, 0, winreg.KEY_ALL_ACCESS)

    try:
        old = winreg.QueryValueEx(hkey, key)
    except:
        old = None

    winreg.SetValueEx(hkey, key, 0, type, value)
    winreg.CloseKey(hkey)    

    return old



if os.path.exists(r"C:\\Users\\siddharth.mungekar\\Desktop\\MemleakTest\\test.xlsm"):

    # Set macro settings to 1 to allow all macros    
    old = registry_set_key(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Office\14.0\Excel\Security', 'VBAWarnings', winreg.REG_DWORD, 1)

    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')

    # If there was an existing value, put it back
    if old:
        registry_set_key(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Office\14.0\Excel\Security', 'VBAWarnings', winreg.REG_DWORD, old[0])

注意,您可能需要根据安装的Office版本调整注册表路径,请使用REGEDIT进行检查。i、 e.确保Office\14.0存在。在

另请查看Microsoft Project – how to control Macro Settings using registry keys以获取更多信息。在

相关问题 更多 >

    热门问题