VBA to Python Syntax Mapping
A complete side-by-side reference for converting Visual Basic for Applications to Python. Every data type, operator, loop, function, and Excel object mapped to its Python equivalent.
Data Types
VBA is statically typed with explicit declarations. Python is dynamically typed, but type hints provide equivalent documentation. The converter preserves Dim declarations as comments for traceability.
| VBA Type | Python Type | Notes |
|---|---|---|
| Integer | int | VBA 16-bit; Python arbitrary precision |
| Long | int | VBA 32-bit; Python arbitrary precision |
| Double | float | 64-bit IEEE 754 in both |
| String | str | VBA strings are mutable; Python strings are immutable |
| Boolean | bool | True/False in both (capitalized in Python) |
| Variant | Any | Avoid in Python; use explicit types |
| Date | datetime | import datetime; different epoch |
| Object | object | COM objects have no direct Python analog |
Variable Declarations
VBA
Dim count As Integer Dim name As String Dim total As Double Dim isValid As Boolean
Python
# Dim count As Integer # Dim name As String # Dim total As Double # Dim isValid As Boolean count: int = 0 name: str = "" total: float = 0.0 is_valid: bool = False
The converter keeps Dim statements as comments so you can trace the original declarations during code review.
Operators
| Operation | VBA | Python |
|---|---|---|
| Equality | = | == |
| Inequality | <> | != |
| Logical AND | And | and |
| Logical OR | Or | or |
| Logical NOT | Not | not |
| String concat | & | + |
| Modulus | Mod | % |
| Integer division | \ | // |
| Exponent | ^ | ** |
Control Flow
The converter handles all standard VBA control flow structures. Each is mapped to its Python equivalent while preserving the original branching logic.
If / ElseIf / Else
VBA
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
Else
grade = "C"
End IfPython
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"For / Next
VBA
For i = 1 To 10
total = total + i
Next i
For j = 10 To 1 Step -1
Debug.Print j
Next jPython
for i in range(1, 10 + 1):
total = total + i
for j in range(10, 1 - 1, -1):
print(j)Note the + 1 adjustment: VBA For loops are inclusive on both ends, while Python's range() excludes the upper bound. See the loops guide for more detail.
Select Case
VBA
Select Case rating
Case "A"
bonus = 1000
Case "B", "C"
bonus = 500
Case Is >= "D"
bonus = 0
Case Else
bonus = 0
End SelectPython
if rating == "A":
bonus = 1000
elif rating in ("B", "C"):
bonus = 500
elif rating >= "D":
bonus = 0
else:
bonus = 0Do While / Do Until
VBA
Do While row <= lastRow
total = total + Cells(row, 1).Value
row = row + 1
Loop
Do Until found = True
' search logic
LoopPython
while row <= lastRow:
total = total + ws.cell(row=row, column=1).value
row = row + 1
while not (found == True):
# search logic
passFor Each
VBA
For Each cell In Range("A1:A10")
If cell.Value <> "" Then
count = count + 1
End If
Next cellPython
for cell in ws["A1:A10"]:
if cell.value != "":
count = count + 1Built-in Function Mapping
The converter maps 53 VBA functions to Python equivalents. Functions with a helper generate a small utility function in the output to handle VBA-specific edge cases like 1-based string indexing. Functions with an import add the appropriate Python module import automatically.
String Functions
| VBA | Python | Type |
|---|---|---|
| Len(s) | len(s) | Direct |
| Trim(s) | s.strip() | Helper |
| LTrim(s) | s.lstrip() | Helper |
| RTrim(s) | s.rstrip() | Helper |
| UCase(s) | s.upper() | Helper |
| LCase(s) | s.lower() | Helper |
| Left(s, n) | s[:n] | Helper |
| Right(s, n) | s[-n:] | Helper |
| Mid(s, start, len) | s[start-1:start-1+len] | Helper |
| InStr(s, find) | s.find(find) + 1 | Helper |
| Replace(s, old, new) | s.replace(old, new) | Helper |
| Split(s, delim) | s.split(delim) | Helper |
| Join(arr, delim) | delim.join(arr) | Helper |
| Asc(c) | ord(c) | Direct |
| Chr(n) | chr(n) | Direct |
| Space(n) | " " * n | Helper |
| StrReverse(s) | s[::-1] | Helper |
| StrComp(s1, s2) | compare function | Helper |
| String(n, c) | c * n | Helper |
Type Conversion & Checking
| VBA | Python | Type |
|---|---|---|
| CStr(v) | str(v) | Direct |
| CInt(v) / CLng(v) | int(v) | Direct |
| CDbl(v) / CSng(v) | float(v) | Direct |
| CBool(v) | bool(v) | Direct |
| CByte(v) | int(v) | Direct |
| Val(s) | parse leading number | Helper |
| IsNumeric(v) | float(v) try/except | Helper |
| IsEmpty(v) | v is None or v == "" | Helper |
| IsNull(v) | v is None | Helper |
| IsDate(v) | datetime parse test | Helper |
| IsArray(v) | isinstance(v, list) | Helper |
| TypeName(v) | type(v).__name__ | Helper |
Math Functions
| VBA | Python | Type |
|---|---|---|
| Abs(n) | abs(n) | Direct |
| Int(n) | math.floor(n) | Helper |
| Fix(n) | math.trunc(n) | Helper |
| Sqr(n) | math.sqrt(n) | import math |
| Round(n, d) | round(n, d) | Direct |
| Rnd() | random.random() | Helper |
| Log(n) | math.log(n) | import math |
| Exp(n) | math.exp(n) | import math |
| Sgn(n) | sign helper | Helper |
Date/Time Functions
| VBA | Python | Type |
|---|---|---|
| Now() | datetime.datetime.now() | import datetime |
| Year(d) | d.year | Helper |
| Month(d) | d.month | Helper |
| Day(d) | d.day | Helper |
| Hour(d) | d.hour | Helper |
| Minute(d) | d.minute | Helper |
| Second(d) | d.second | Helper |
| DateSerial(y, m, d) | date(y, m, d) | Helper |
| DateAdd(i, n, d) | timedelta arithmetic | Helper |
| DateDiff(i, d1, d2) | delta calculation | Helper |
| DateValue(s) | datetime.strptime() | Helper |
Array & I/O Functions
| VBA | Python | Type |
|---|---|---|
| Array(1, 2, 3) | list(args) | Helper |
| UBound(arr) | len(arr) - 1 | Helper |
| LBound(arr) | 0 | Helper |
| MsgBox(msg) | print(msg) | Direct |
| InputBox(prompt) | input(prompt) | Direct |
| Format(v, fmt) | format(v, fmt) | Direct |
| Environ(name) | os.environ.get(name) | Helper |
| RGB(r, g, b) | RGB(r, g, b) | Direct |
See the string functions guide for detailed examples and edge cases for each string helper.
Constants
| VBA Constant | Python Value |
|---|---|
| vbCrLf | "\n" |
| vbCr | "\r" |
| vbNewLine | "\n" |
| vbLf | "\n" |
| vbTab | "\t" |
| vbNullString | "" |
| vbNullChar | "\0" |
| Nothing | None |
| Empty | None |
| Null | None |
| True | True |
| False | False |
Excel Object Model (openpyxl)
The converter translates VBA Excel objects to openpyxl equivalents. Every converted Sub or Function receives a ws (worksheet) parameter automatically.
| VBA | Python (openpyxl) |
|---|---|
| Range("A1").Value | ws["A1"].value |
| Range("A1:B5") | ws["A1:B5"] |
| Cells(i, j).Value | ws.cell(row=i, column=j).value |
| ActiveSheet | ws |
| Rows.Count | ws.max_row |
| Set obj = Nothing | obj = None |
What Needs Manual Review
The converter flags these constructs with TODO comments and warnings rather than guessing at translations that could introduce bugs.
Flagged for Refactoring
- ⚠ GoTo labels and jumps
- ⚠ On Error Resume Next
- ⚠ ReDim Preserve dynamic arrays
See the GoTo guide and arrays guide.
Not Supported
- ✕ UserForms and ActiveX controls
- ✕ Third-party DLL/COM references
- ✕ Class module events
- ✕ .Find(), .Sort(), .AutoFilter
Subs and Functions
VBA
Sub ProcessData()
' Sub with no return value
End Sub
Function AddTax(price As Double) As Double
AddTax = price * 1.1
End FunctionPython
def ProcessData(ws):
# Sub with no return value
pass
def AddTax(ws, price):
return price * 1.1The converter automatically adds a ws parameter for worksheet access and converts FunctionName = value return patterns to return value.
Error Handling
VBA
On Error GoTo ErrHandler
' risky code
Exit Sub
ErrHandler:
MsgBox Err.DescriptionPython (manual refactor)
try:
# risky code
except Exception as e:
print(str(e))The converter flags On Error statements for manual review because VBA error handling is structurally different from Python exceptions. See the GoTo and error handling guide for refactoring strategies.
Frequently Asked Questions
Is Python faster than VBA?
For data processing, yes. Python with pandas can process millions of rows in seconds. VBA processes cells one at a time and slows down significantly past 10,000 rows. For simple worksheet operations, the difference is negligible.
Can Python replace VBA in Excel?
Python can replace most VBA automation tasks using libraries like openpyxl (read/write .xlsx files) or xlwings (interact with a running Excel instance). However, Python cannot run inside the Excel VBA editor — it runs as an external script.
What Python library replaces VBA?
openpyxl for reading and writing Excel files without Excel installed. xlwings for controlling a running Excel application. pandas for data analysis and transformation. The VBAtoPython converter outputs openpyxl-based code.
Does Python use 0-based or 1-based indexing?
Python uses 0-based indexing. VBA collections and arrays typically use 1-based indexing. This is the most common source of off-by-one bugs during migration. The converter adjusts For loop ranges and string function indices automatically.
Can I convert VBA to Python automatically?
Yes, for standard constructs like loops, conditionals, string functions, and Range/Cells operations. Complex patterns like GoTo jumps, On Error handling, and COM object calls are flagged for manual review. Try the converter to see what percentage of your macro converts cleanly.
Related Guides
- Complete Migration Guide — Step-by-step process for migrating a full VBA project to Python.
- Excel VBA to Python with openpyxl — Deep dive into Range, Cells, and worksheet operations.
- VBA String Functions in Python — Trim, Left, Mid, InStr, Replace with edge cases and examples.
- VBA Loops to Python — For, For Each, Do While, Do Until with the range() gotcha.
Try it on your own code
Paste a VBA macro into the converter and see the Python output instantly. Free tier converts up to 25 lines.