简体   繁体   English

如何从 Python 运行 Excel VBA / 宏

[英]How to run Excel VBA / Macro from Python

I am trying to run a VBA Macro in an xlsm workbook using python 3.7 in Spyder.我正在尝试使用 Spyder 中的 python 3.7 在 xlsm 工作簿中运行 VBA 宏。 This workbook has two worksheets.此工作簿有两个工作表。

The code that I have currently runs and saves the new file with no problems, however it is not triggering the VBA like it should.我当前运行的代码没有问题地保存新文件,但是它没有像它应该那样触发 VBA。

I know this macro works because if I manually click the button in Excel, it works just fine.我知道这个宏有效,因为如果我手动单击 Excel 中的按钮,它就可以正常工作。

Could someone assist with this?有人可以帮忙吗? I checked the Macro Settings under the Trust Center and all macros are enabled so I do not think it is a permissions issue, however I am not an admin on this pc.我检查了信任中心下的宏设置并启用了所有宏,所以我认为这不是权限问题,但我不是这台电脑的管理员。

The code is below:代码如下:

import os
import win32com.client

xl = win32com.client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open("Z:\FolderName\FolderName2\FileName.xlsm")
xl.Application.Run("MacroName")
wb.SaveAs("Z:\FolderName\FolderName2\FileName1.xlsm")
wb.Close()
xl.Quit()

This can be done easily through xlwings.这可以通过 xlwings 轻松完成。 Once I switched to that library then I was able to quickly get this script working.一旦我切换到那个库,我就能够快速地让这个脚本工作。

You need to reference the module name as well您还需要引用模块名称


Example here my vba code under Module1此处示例我在 Module1 下的 vba 代码

Option Explicit
Public Sub Example()
    MsgBox "Hello 0m3r"
End Sub

and here is my python这是我的 python


from win32com.client import Dispatch


def run_excel_macro():
    try:
        excel = Dispatch("Excel.Application")
        excel.Visible = True
        workbook = excel.Workbooks.Open(
            r"D:\Documents\Book1.xlsm")

        workbook.Application.Run("Module1.Example")
        workbook.SaveAs(r"D:\Documents\Book5.xlsm")
        excel.Quit()
    except IOError:
        print("Error")


if __name__ == "__main__":
    run_excel_macro()

First make sure you have your All.xlsm file in your current working or in your User/Documents(Sometimes it working from yourDocuments directory and sometimes not, so better to have in both)首先确保您在当前工作或用户/文档中有 All.xlsm 文件(有时它在 yourDocuments 目录中工作,有时不在,所以最好两者都有)

pass your macro name along with the file name that contains the macro you can make change to Parameters like ReadOnly or Savechanges according to your requirement将您的宏名称与包含宏的文件名一起传递,您可以根据您的要求更改 ReadOnly 或 Savechanges 等参数

And be make sure to deleta xl object after each run并确保在每次运行后删除 xl object

import win32com.client

xl =win32com.client.dynamic.Dispatch('Excel.Application')
xl.Workbooks.Open(Filename = XYZ.xls, ReadOnly= 1)
xl.Application.Run('All.xlsm!yourmacroname')
xl.Workbooks(1).Close(SaveChanges=1)
xl.Application.Quit()
del xl

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

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