如何使用 xlwings 从 Python 调用 Excel 宏? [英] How do I call an Excel macro from Python using xlwings?

查看:78
本文介绍了如何使用 xlwings 从 Python 调用 Excel 宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了 xlwings 的 API 文档,并使用了 Workbook 和 Sheet 对象在解释器中,但我不知道如何从 Python 调用宏.

如何使用 xlwings 从 Python 调用 Excel 宏?

解决方案

这还没有实现,但有一个未解决的问题,请参阅 此处.与此同时,你可以像这样解决它(这是针对 Windows,但 Mac 版本相应地工作,再次在 问题):

from xlwings import Workbookwb = 工作簿(...)wb.application.xl_app.Run("your_macro")

更新:对于更新的版本,您必须:

from xlwings import Workbook, Applicationwb = 工作簿(...)应用程序(wb).xl_app.Run("your_macro")

更新 2:现在从 >=v0.7.1 开始支持此功能.让我们假设,有一个 VBA 函数 YourMacro 将两个数字相加:

<预><代码>>>>将 xlwings 导入为 xw>>>wb = xw.Book(r'C:path omybook.xlsm')>>>your_macro = wb.macro('YourMacro')>>>your_macro(1, 2)3.0

I've read the API docs for xlwings, and played around with Workbook and Sheet objects in the interpreter, but I can't figure out how to call a macro from Python.

How do I use xlwings to call an Excel macro from Python?

解决方案

This is not implemented yet, but there's an open issue for it, see here. In the meantime, you can work around it like so (this is for Windows, but the Mac version works accordingly, see again in the issue):

from xlwings import Workbook
wb = Workbook(...)
wb.application.xl_app.Run("your_macro")

update: for more recent versions, you have to do:

from xlwings import Workbook, Application
wb = Workbook(...)
Application(wb).xl_app.Run("your_macro")

update 2: This functionality is now natively supported from >=v0.7.1. Let's assume, there is a VBA function YourMacro that sums up two numbers:

>>> import xlwings as xw
>>> wb = xw.Book(r'C:path	omybook.xlsm')
>>> your_macro = wb.macro('YourMacro')
>>> your_macro(1, 2)
3.0

这篇关于如何使用 xlwings 从 Python 调用 Excel 宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆