Excel VBA to Python with openpyxl
A practical guide to replacing Excel VBA macros with Python scripts. Learn how Range, Cells, formatting, and worksheet operations translate to openpyxl — the library the converter engine targets.
Why Move Excel Macros to Python?
- Version control: Python files are plain text — track every change in Git instead of hiding logic inside
.xlsmbinaries. - Testing: Write unit tests with pytest. VBA has no built-in test framework.
- Scalability: Python scripts run on servers, CI/CD pipelines, and containers. VBA requires a desktop Excel instance.
- No Excel dependency: openpyxl reads and writes
.xlsxfiles without Excel installed — perfect for Linux servers and Docker. - Modern ecosystem: Combine openpyxl with pandas, SQLAlchemy, or any Python library in one script.
Choosing a Python Library for Excel
Three libraries cover most VBA replacement scenarios. The VBAtoPython converter outputs openpyxl-based code because it works everywhere without requiring a running Excel instance.
| Library | Best For | Needs Excel? | Platform |
|---|---|---|---|
| openpyxl | Reading/writing .xlsx files, cell formatting, formulas | No | Any (Windows, Mac, Linux) |
| xlwings | Controlling a running Excel app, real-time interaction | Yes | Windows, Mac |
| pandas | Data analysis, bulk transformations, pivot-style operations | No | Any |
Rule of thumb: Use openpyxl when you care about the spreadsheet (cell placement, formatting, specific ranges). Use pandas when you care about the data (filtering, aggregation, analysis). Use xlwings when you need to automate a live Excel session.
Range and Cells Mapping
These are the most common VBA operations. The converter handles all of them automatically.
Reading and Writing Values
VBA
' Read a single cell
x = Range("A1").Value
' Write to a cell
Range("B2").Value = 42
' Read with Cells()
val = Cells(row, col).Value
' Write with Cells()
Cells(row, col).Value = "done"Python (openpyxl)
# Read a single cell x = ws["A1"].value # Write to a cell ws["B2"].value = 42 # Read with cell() val = ws.cell(row=row, column=col).value # Write with cell() ws.cell(row=row, column=col).value = "done"
Looping Through Cells
VBA
Sub CleanColumn()
Dim i As Long
For i = 2 To 100
If Cells(i, 1).Value <> "" Then
Cells(i, 2).Value = Trim(Cells(i, 1).Value)
End If
Next i
End SubPython (converter output)
import openpyxl
def vba_trim(s):
return str(s).strip()
def CleanColumn(ws):
# Dim i As Long
for i in range(2, 100 + 1):
if ws.cell(row=i, column=1).value != "":
ws.cell(row=i, column=2).value = vba_trim(
ws.cell(row=i, column=1).value)Cell Formatting
VBA
Cells(i, 1).Interior.Color = RGB(255, 0, 0)
Python (openpyxl)
from openpyxl.styles import PatternFill
ws.cell(row=i, column=1).fill = PatternFill(
start_color="FF0000", fill_type="solid"
)Complete Workflow: Running a Converted Macro
After converting your VBA macro, wrap it in a Python script that opens the workbook, runs the logic, and saves the result.
Python — complete script
import openpyxl
# -- paste your converted functions here --
def CalcBonus(ws):
score = ws["B2"].value
if score >= 90:
bonus = 1000
elif score >= 70:
bonus = 500
else:
bonus = 0
ws["C2"].value = bonus
# -- main entry point --
wb = openpyxl.load_workbook("data.xlsx")
ws = wb.active
CalcBonus(ws)
wb.save("data_output.xlsx")
print("Done — saved to data_output.xlsx")What the Converter Handles Automatically
Fully Converted
- ✓ Range("A1").Value reads and writes
- ✓ Cells(row, col).Value reads and writes
- ✓ Interior.Color with RGB()
- ✓ For loops through cell ranges
- ✓ ActiveSheet references
- ✓ Rows.Count for last row
Flagged for Manual Work
- ⚠ .Find() and .FindNext()
- ⚠ .Sort() with parameters
- ⚠ .AutoFilter criteria
- ⚠ Cells().End(xlUp).Row patterns
- ⚠ Range.Copy / Range.Paste
Frequently Asked Questions
Does openpyxl support macros?
openpyxl cannot run VBA macros. It reads and writes cell data, formatting, and formulas in .xlsx files. The purpose of converting to Python is to replace the macro logic entirely with a Python script.
Can Python run inside Excel?
Microsoft's 'Python in Excel' feature runs Python in the cloud via Microsoft 365. For full local control, run your converted scripts as standalone Python programs that open and modify Excel files via openpyxl.
Is openpyxl the same as xlwings?
No. openpyxl reads/writes .xlsx files without needing Excel installed. xlwings controls a live Excel application. openpyxl is better for server-side automation; xlwings is better when you need real-time Excel interaction.
Can I convert .xlsm files?
Export the VBA modules from the .xlsm (via VBA Editor → Export File), then convert the .bas files. openpyxl can read .xlsm data but cannot execute or preserve the embedded VBA code.
Related Guides
- Complete Syntax Mapping Reference — Every VBA construct mapped to Python.
- VBA Loops to Python — For, For Each, Do While with cell iteration patterns.
- VBA String Functions in Python — Trim, Left, Mid, InStr — commonly used in cell processing.
Convert your Excel macros now
Paste a VBA macro and see the openpyxl Python output instantly.