VBA Syntax Basics: Variables, Loops, Conditionals

Master three things and you can write 80% of VBA macros: declare variables, branch on conditions, loop.

Variable Declaration

vba
Dim i As Integer Dim name As String Dim total As Double

Add Option Explicit to force declaration and catch typos.

Conditionals

vba
If score >= 90 Then MsgBox "Excellent" ElseIf score >= 60 Then MsgBox "Pass" Else MsgBox "Fail" End If

Use Select Case for many branches.

Loops

vba
' For loop For i = 1 To 10 total = total + i Next i ' For Each over a collection For Each cell In Range("A1:A10") cell.Value = cell.Value * 2 Next cell

Comparison

Scenario Recommended
Known count For
Iterate a collection For Each
Condition-driven Do While

Tools

Want to convert finished code to Python? The online converter translates For/If/Dim automatically.