VbaConditionalsBeginner

If...Then...Else

Branches macro logic based on a condition.

Review the syntaxStudy the examplesOpen the coding app
If condition Then
    ' statements
Else
    ' fallback
End If

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Branches macro logic based on a condition.

If...Then...Else is the default branching tool for workbook automation: validate input, guard destructive actions, skip blanks, or route records into different sheets. It is the right tool for a small number of explicit conditions, while Select Case becomes clearer when you are routing among many discrete values.

Quick reference

Syntax

If condition Then
    ' statements
Else
    ' fallback
End If

See it in practice

Examples

1

Skip blank customer codes

If Len(Trim$(Cells(2, 1).Value)) = 0 Then
    MsgBox "Customer code is missing"
Else
    Call ProcessCustomer
End If

Conditionals are essential for safe workbook automation on messy input data.

Debug faster

Common Errors

1

LogicError

Cause: Testing worksheet values without trimming spaces or handling Empty values first.

Fix: Normalize the input before the condition when imported data may be messy.

Runtime support

Compatibility

Excel desktop VBA

Source: Microsoft Learn Office VBA reference

Common questions

Frequently Asked Questions

Branches macro logic based on a condition.

LogicError: Normalize the input before the condition when imported data may be messy.