Guide
xlwings Run Macro from Python Example
To run a VBA macro from Python using xlwings, instantiate an xw.App object, open the target workbook, bind the subroutine with app.macro(), and invoke it as a callable. This method routes directly through Excel’s COM (Windows) or AppleScript (macOS) bridge, providing the most reliable execution path for Python developers automating legacy reporting pipelines. For foundational concepts on workbook lifecycle and object mapping, review Getting Started with Python Excel Automation before integrating macro calls into scheduled jobs.
xlwings Run Macro from Python Example
To run a VBA macro from Python using xlwings, instantiate an xw.App object, open the target workbook, bind the subroutine with app.macro(), and invoke it as a callable. This method routes directly through Excel’s COM (Windows) or AppleScript (macOS) bridge, providing the most reliable execution path for Python developers automating legacy reporting pipelines. For foundational concepts on workbook lifecycle and object mapping, review Getting Started with Python Excel Automation before integrating macro calls into scheduled jobs.
Working Code Example
The following pattern handles workbook lifecycle, macro binding, and resource cleanup safely. It assumes your VBA subroutine resides in a standard module and accepts optional positional arguments.
import xlwings as xw
from pathlib import Path
def run_excel_macro(workbook_path: str, macro_name: str, *args):
"""Open a workbook, execute a VBA macro, and clean up resources."""
app = xw.App(visible=False) # Set True to debug VBA UI or dialogs
try:
wb = app.books.open(str(Path(workbook_path).resolve()))
# Bind macro using 'WorkbookName!MacroName' syntax
macro = app.macro(f"'{wb.name}'!{macro_name}")
macro(*args) # Pass parameters positionally
wb.save()
except Exception as e:
print(f"Macro execution failed: {e}")
raise
finally:
wb.close()
app.quit()
# Usage
run_excel_macro("C:/reports/monthly_summary.xlsm", "FormatAndExport", True)
Compatibility & Requirements
- xlwings Version:
>=0.24.0. Theapp.macro()API replacedwb.macro()for consistent scope resolution. - Python Version:
3.8+recommended for stablepathliband type-hint support. - Excel Version:
2016+or Microsoft 365. Windows relies onpywin32; macOS usesappscript/osascript. - File Format: Must be
.xlsm,.xlsb, or.xlam. Standard.xlsxfiles cannot store VBA. - Macro Security: Enable macros via
File > Options > Trust Center > Macro Settingsor place the workbook in a Trusted Location. Untrusted files will trigger security prompts that hang headless execution. - Cross-Platform: Avoid Windows-specific COM constants. Test with
visible=Trueduring development to surface silent VBA errors.
Troubleshooting Common Errors
com_error / pywintypes.com_error or AppleEventTimeoutError
Excel is hung, blocked by security, or already locked by another process. Fix: Add app.display_alerts = False before opening, terminate orphaned EXCEL.EXE processes (taskkill /F /IM EXCEL.EXE), and verify paths use forward slashes or raw strings.
AttributeError: 'App' object has no attribute 'macro'
Your xlwings installation is outdated. Run pip install --upgrade xlwings. Pre-0.24 versions used the deprecated wb.macro() method.
Macro Not Found or NameError in VBA
Excel resolves macros strictly via 'WorkbookName!MacroName'. For personal macros, use app.macro("'Personal.xlam'!MyRoutine"). Wrap workbook names containing spaces in single quotes.
Headless/Server Execution Fails
xlwings requires a licensed desktop Excel installation. It cannot run in pure cloud environments (AWS Lambda, Docker without GUI, GitHub Actions). Fallback: Port VBA logic to pandas/openpyxl, or use win32com.client on Windows-only infrastructure.
Argument Passing Mismatch
xlwings passes arguments positionally only. Map VBA Optional parameters to None or "". Keyword arguments are unsupported. When aligning Python Range objects with VBA expectations, reference the Automating Excel with xlwings Basics guide for proper sheet and cell mapping.