Driving Excel itself
Macros & VBA
Running macros from Python, keeping .xlsm files intact, and replacing VBA with Python.
Step-by-step how-tos
One task each, with code you can copy, run and adapt.
- How-toAdd a VBA Macro to a Workbook with xlsxwriterShip a macro-enabled .xlsm report from Python: extract a vbaProject.bin once from a workbook saved in Excel, attach it to every new file with xlsxwriter, wire a button to a macro, keep the workbook and sheet code names consistent, and check the result without opening Excel.
- How-toExtract VBA Macro Code from an Excel FileRead the VBA inside .xlsm, .xlsb and .xls files without opening Excel: detect whether a workbook has macros at all, extract every module with oletools, save them as .bas and .cls files that can be diffed and reviewed in git, inventory the macros across a folder, and flag suspicious code before anyone enables it.
- How-toRun an Excel Macro from Python with win32comCall existing VBA from Python with Application.Run: qualified macro names, positional arguments, return values, and staging bulk data so the loop runs inside Excel.
- How-toCall Python from Excel with an xlwings UDFExpose a Python function as a worksheet formula with xlwings — the add-in setup, @xw.func and @xw.arg decorators, array and DataFrame arguments, and the Windows-only limits.
- How-toxlwings: Run a VBA Macro From Python (Example)A complete xlwings example for running a VBA macro from Python: open the workbook, bind the Sub with app.macro() or book.macro(), pass arguments, save, and quit Excel.
- How-toTranslate Common VBA Macros to PythonA phrasebook for moving VBA to Python: the eight patterns that make up most Excel macros — finding the last row, looping over rows, deleting rows that match, lookups with a dictionary, filtering and copying, looping over a folder of files, saving a copy with a date, and error handling — each shown in VBA and in pandas or openpyxl.
- How-toRun Python from an Excel Button with xlwings RunPythonLet Excel users run your Python code with a button — xlwings quickstart, the RunPython VBA call, Book.caller() to reach the calling workbook, passing arguments, configuring the interpreter, testing with a mock caller, and distributing the workbook.
- How-toWork with Macro-Enabled .xlsm Files in openpyxlEdit .xlsm workbooks from Python without destroying the VBA project: the keep_vba flag, why the filename matters, what openpyxl still drops, and how to verify macros survived.
Compare the options
Which tool or approach to pick, and why.
Follow it through a track
Prefer an ordered route? These tracks cover macros & vba along the way, in the order that builds on itself.
Related topics
Subjects that keep turning up on the same pages as this one, most overlap first.
Macros & VBA is part of Driving Excel itself.