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
vbaDim i As Integer
Dim name As String
Dim total As DoubleAdd Option Explicit to force declaration and catch typos.
Conditionals
vbaIf score >= 90 Then
MsgBox "Excellent"
ElseIf score >= 60 Then
MsgBox "Pass"
Else
MsgBox "Fail"
End IfUse 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 cellComparison
| 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.