How to call an Excel macro from Python using xlwings?

I have read the API docs for xlwings and played around with Workbook and Sheet objects in the interpreter, but I cannot figure out how to call the macro from Python.

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

+3


source to share


3 answers


It hasn't been implemented yet, but there is an open issue for that, see here . In the meantime, you can work around it like this (this is for Windows, but the Mac version works accordingly, see again in issue ):

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

      

update : for more recent versions, you need to do the following:



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

      

update 2 : This functionality is now supported from> = v0.7.1. Suppose there is a VBA function YourMacro

that adds 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

      

+6


source


I know this is a late answer, but all the methods above did not work for me. But I found another way using awesome api provided by xlwings.

Here is my code that I used to run the macro:

xlApp = xw.App(visible=False)
wb= xw.books.open('.\\Path\\To\\File.xlsm')
a = xlApp.api.Application.Run("macroTest")

      



My macro opened MsgBox and returned a value of 1 just for the test, and it worked pretty well. Although you should avoid using MsgBox as it was open in the background.

Btw. The api is available in many (if not all) objects and is really powerful if you are used to VBA programming.

+1


source


I was having problems when I updated xlwings to 0.9+ version. To run a vba macro using xlwings I used the below code to run macros inside a personal ledger (PERSONAL.XLSB). Felix's updated code # 2 did not work for me for a macro inside a personal ledger.

import xlwings

wb = xw.Book(excel_file_path)
app = wb.app
# into brackets, the path of the macro
macro_vba = app.macro("'PERSONAL.XLSB'!my_macro") 
macro_vba()

      

Hope this helps.

0


source







All Articles