Budd Budd - 10 months ago 110
Python Question

How do I call an Excel VBA script using xlwings v0.10

I used to use the info in this question to run a VBA script that does some basic formatting after I run my python code.

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

Specifically I used the first update.

from xlwings import Workbook, Application
wb = Workbook(...)

Now I'm using v0.10.0 of xlwings and this code no longer works.

When I try the suggested new code for v0.10.0:


Python returns an object:

<xlwings.main.Macro at 0x92d3198>

and my macro isn't run in Excel.

The documentation (http://docs.xlwings.org/en/stable/api.html#xlwings.App.macro) has an example that is a custom function but I have a script that does several things in Excel (formats the data I output from python, adds some formulas in the sheet, etc.) that I want to run.

I'm sure I'm missing something basic here.

Based on Felix Zumstein's suggestion, I tried:

import xlwings as xw
xlfile = 'model.xlsm'
wb = xw.Book(xlfile)

This returns the same thing as wb.app.macro('your_macro'):

<xlwings.main.Macro at 0x92d05888>

and no VBA script run inside Excel.

Answer Source

You need to use Book.macro. As your link to the docs says, App.macro is only for macros that are not part of a workbook (i.e. addins). So use:

your_macro = wb.macro('your_macro')  # this maps the VBA code
your_macro()  # only this executes the VBA code