ABM
ABM

Reputation: 1628

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?

Upvotes: 11

Views: 32926

Answers (5)

kiki270
kiki270

Reputation: 71

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.

Upvotes: 5

Sasha18
Sasha18

Reputation: 65

Extending @Felix Zumstein's answer and all other answers here, please ensure you have disabled Macro settings as you may face COM issues later.

You can change that under,

File > Options > Trust Center > Trust Center Settings > Macro Settings > Enable all macros (not recommended...)

Upvotes: 0

Myeongsik Joo
Myeongsik Joo

Reputation: 609

Another simple way if you already open a excel.

xw.apps.active.macro('yourMacro')(1, 2)

Upvotes: 0

Felix Zumstein
Felix Zumstein

Reputation: 7070

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

Upvotes: 19

Krossi
Krossi

Reputation: 81

I know it is a late answer, but all the ways posted above didn't work for me. But I have found another way, by using the awesome api-interface provided by xlwings.

Here is my code I used to run a macro:

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

My macro opened a MsgBox and returned the value 1 just for test and it worked very well. Although one should avoid using MsgBox, since it was opened in background.

Btw. the api-interface is available in many (when not all) objects and it is really powerfull if you are used to VBA programming.

Upvotes: 1

Related Questions