VBAtoPython
Start Conversion
← All articles

VBA to Python Cheat Sheet (2026)

One-page quick reference for converting VBA to Python. Side-by-side syntax for variables, loops, functions, strings, dates, files, Excel operations, and error handling.

A concise side-by-side reference for converting VBA to Python. Bookmark this page and use it alongside your migration work.

Variables and Types

| VBA | Python | |-----|--------| | Dim x As Integer | x = 0 | | Dim s As String | s = "" | | Dim d As Double | d = 0.0 | | Dim b As Boolean | b = False | | Dim dt As Date | dt = datetime.date.today() | | Const PI = 3.14 | PI = 3.14 | | Set obj = Nothing | obj = None |

Type Conversion

| VBA | Python | |-----|--------| | CInt(x) | int(x) | | CLng(x) | int(x) | | CDbl(x) | float(x) | | CStr(x) | str(x) | | CBool(x) | bool(x) | | Val("123") | float("123") | | Int(-3.7) (floor) | math.floor(-3.7) | | Fix(-3.7) (truncate) | int(-3.7) |

String Functions

| VBA | Python | |-----|--------| | Len(s) | len(s) | | Left(s, 3) | s[:3] | | Right(s, 3) | s[-3:] | | Mid(s, 2, 4) | s[1:5] | | InStr(s, "find") | s.find("find") + 1 | | InStrRev(s, "find") | s.rfind("find") + 1 | | Replace(s, "a", "b") | s.replace("a", "b") | | Trim(s) | s.strip() | | LTrim(s) / RTrim(s) | s.lstrip() / s.rstrip() | | UCase(s) / LCase(s) | s.upper() / s.lower() | | Split(s, ",") | s.split(",") | | Join(arr, ",") | ",".join(arr) | | Chr(65) | chr(65) | | Asc("A") | ord("A") | | StrReverse(s) | s[::-1] | | Space(10) | " " * 10 | | String(5, "x") | "x" * 5 |

Note: VBA string functions use 1-based indexing. Python uses 0-based. Mid(s, 2, 4) starts at position 2, which is s[1:5] in Python.

Math Functions

| VBA | Python | |-----|--------| | Abs(x) | abs(x) | | Sqr(x) | math.sqrt(x) | | Round(x, 2) | round(x, 2) | | Sgn(x) | (x > 0) - (x < 0) | | Rnd() | random.random() | | Randomize | random.seed() | | Log(x) | math.log(x) | | Exp(x) | math.exp(x) | | x Mod y | x % y | | x ^ y | x ** y |

Date Functions

| VBA | Python | |-----|--------| | Now | datetime.datetime.now() | | Date | datetime.date.today() | | Year(d) | d.year | | Month(d) | d.month | | Day(d) | d.day | | Hour(d) | d.hour | | DateAdd("d", 7, d) | d + timedelta(days=7) | | DateDiff("d", d1, d2) | (d2 - d1).days | | DateSerial(2024, 1, 15) | datetime.date(2024, 1, 15) | | Format(d, "yyyy-mm-dd") | d.strftime("%Y-%m-%d") |

Control Flow

If / ElseIf / Else

' VBA
If x > 10 Then
    MsgBox "big"
ElseIf x > 5 Then
    MsgBox "medium"
Else
    MsgBox "small"
End If
# Python
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")

For Loop

' VBA
For i = 1 To 10
    Debug.Print i
Next i
# Python
for i in range(1, 11):
    print(i)

For Each

' VBA
For Each item In collection
    Debug.Print item
Next item
# Python
for item in collection:
    print(item)

Do While / Do Until

' VBA
Do While x < 10
    x = x + 1
Loop

Do Until x >= 10
    x = x + 1
Loop
# Python
while x < 10:
    x += 1

while not (x >= 10):
    x += 1

Select Case

' VBA
Select Case grade
    Case "A": MsgBox "Excellent"
    Case "B", "C": MsgBox "Good"
    Case Else: MsgBox "Other"
End Select
# Python
if grade == "A":
    print("Excellent")
elif grade in ("B", "C"):
    print("Good")
else:
    print("Other")

Functions and Subs

' VBA
Sub DoWork(name As String, Optional count As Integer = 1)
    ' ...
End Sub

Function Add(a As Double, b As Double) As Double
    Add = a + b
End Function
# Python
def do_work(name, count=1):
    # ...
    pass

def add(a, b):
    return a + b

Error Handling

' VBA
On Error GoTo ErrHandler
    ' risky code
    Exit Sub
ErrHandler:
    MsgBox Err.Description
# Python
try:
    # risky code
    pass
except Exception as e:
    print(str(e))

Dictionary / Collection

| VBA | Python | |-----|--------| | Set d = CreateObject("Scripting.Dictionary") | d = {} | | d.Add "key", "value" | d["key"] = "value" | | d.Item("key") | d["key"] | | d.Exists("key") | "key" in d | | d.Count | len(d) | | d.Keys | list(d.keys()) | | d.Remove "key" | del d["key"] | | d.RemoveAll | d.clear() |

Excel / openpyxl Operations

| VBA | Python (openpyxl) | |-----|--------| | Range("A1").Value = 42 | ws["A1"].value = 42 | | Cells(1, 2).Value | ws.cell(row=1, column=2).value | | ActiveSheet | ws = wb.active | | Worksheets("Sheet1") | ws = wb["Sheet1"] | | Cells(Rows.Count,1).End(xlUp).Row | ws.max_row | | .Font.Bold = True | cell.font = Font(bold=True) | | .Interior.Color = RGB(255,0,0) | cell.fill = PatternFill("solid", fgColor="FF0000") | | .NumberFormat = "#,##0.00" | cell.number_format = "#,##0.00" |

File I/O

' VBA (legacy)
Open "file.txt" For Input As #1
Line Input #1, line
Close #1

' VBA (FSO)
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("file.txt") Then ...
# Python
with open("file.txt", "r") as f:
    line = f.readline()

# File checks
import os
if os.path.isfile("file.txt"):
    ...

Operators

| VBA | Python | |-----|--------| | And | and | | Or | or | | Not | not | | Xor | ^ | | Mod | % | | <> | != | | = (comparison) | == | | & (concatenate) | + or f-string | | Is Nothing | is None | | Like "A*" | re.match(r"A.*", s) |

Common Constants

| VBA | Python | |-----|--------| | vbCrLf | "\n" | | vbTab | "\t" | | vbNullString | "" | | True / False | True / False | | Nothing | None | | Empty | None |

MsgBox / InputBox

| VBA | Python | |-----|--------| | MsgBox "Hello" | print("Hello") | | InputBox("Name?") | input("Name?") | | Debug.Print x | print(x) |


Need to convert a full VBA module? Try the converter free for up to 100 lines. Every conversion is verified with Python's ast.parse() for syntax correctness.