简体   繁体   English

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

[英]How to run an Excel macro using a Python script?

I want to run a macro in an Excel file using a Python script. 我想使用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')

The script fails after opening an Excel file and gives the following error: 打开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. C:\\ Users \\ siddharth.mungekar \\ AppData \\ Local \\ Programs \\ Python \\ Python36 \\ python.exe C:/Users/siddharth.mungekar/PycharmProjects/MacroViaPython/ExcelMacroEnabler.py Traceback(最近一次调用是最近的):文件“ C: /Users/siddharth.mungekar/PycharmProjects/MacroViaPython/ExcelMacroEnabler.py”,xl.Run('Mem_Leak')文件“”的第14行,运行文件“ C:\\ Users \\ siddharth.mungekar \\ AppData \\”中的第14行当地\\程序\\ Python的\\ Python36 \\ LIB \\站点包\\ win32com \\客户端\\ dynamic.py”,线287,在ApplyTypes导致=自我。 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) oleobj .InvokeTypes(*(dispid,LCID,wFlags,retType,argTypes)+ args)pywintypes.com_error:(-2147352567,'发生异常。',(0,'Microsoft Excel',“无法运行宏'Mem_Leak'。该宏可能在此工作簿中不可用,或者可能禁用了所有宏。“,'xlmain11.chm',0,-2146827284),无)

I tried modifying the Trust Centre setting. 我尝试修改信任中心设置。

The code works when another Excel file has already been manually opened. 当已经手动打开另一个Excel文件时,该代码有效。

I tried opening a dummy Excel file and then opening the target Excel file and running the macro. 我尝试打开一个虚拟Excel文件,然后打开目标Excel文件并运行宏。 This did not work. 这没有用。 The dummy excel file has to be opened manually. 虚拟excel文件必须手动打开。

You could try updating the Macro settings in the registry to allow all macros to run. 您可以尝试更新注册表中的“宏”设置,以允许所有宏运行。 You would need to either run your Python script as an administrator, or ensure that the registry key has suitable permissions: 您将需要以管理员身份运行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])

Note, you might need to adjust the registry path depending on the version of Office installed, use REGEDIT to check. 注意,您可能需要根据安装的Office版本调整注册表路径,请使用REGEDIT进行检查。 ie make sure that Office\\14.0 is present. 即确保存在Office\\14.0

Also take a look at Microsoft Project – how to control Macro Settings using registry keys for more information. 另请参阅Microsoft Project –如何使用注册表项控制宏设置,以获取更多信息。

I fixed this issue by putting my macro inside a new module instead of having it in "ThisWorkbook" and by calling: 我通过将宏放在新模块中而不是在“ ThisWorkbook”中并通过调用来解决了此问题:

xl.Run("Module1.UpdateTable")

Full code: 完整代码:

import os
import win32com.client

sXlFile = "C:\\Desktop\\test.xlsm"
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath(sXlFile))
try:
  xl.Run("Module1.UpdateTable")
except Exception as e:
  print(e)

xl.Application.Quit() # Comment this out if your excel script closes
del xl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM