Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 461
ABM Avatar asked May 18 '15 16:05

ABM


People also ask

How do I import Xlwings into Python?

Call Python from Excel To make this run, just import the VBA module xlwings. bas in the VBA editor (Open the VBA editor with Alt-F11, then go to File > Import File... and import the xlwings. bas file. ). It can be found in the directory of your xlwings installation.


2 Answers

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
like image 187
Felix Zumstein Avatar answered Sep 22 '22 02:09

Felix Zumstein


I got issues when I updated xlwings to 0.9+ version. To run vba macro with xlwings, I used the code written below for running macros inside the personal workbook (PERSONAL.XLSB). The updated code no2 of Felix didn't work for me, for macro inside the personal workbook.

import xlwings as xw

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 it will help.

like image 21
kiki270 Avatar answered Sep 22 '22 02:09

kiki270