How do I call an Excel macro from Python using xlwings?

前端 未结 5 799
孤独总比滥情好
孤独总比滥情好 2020-11-27 20:11

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.

H

5条回答
  •  不知归路
    2020-11-27 20:20

    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\to\mybook.xlsm')
    >>> your_macro = wb.macro('YourMacro')
    >>> your_macro(1, 2)
    3.0
    

提交回复
热议问题