Courses โ€บ Logic & Loops

If, ElseIf and Else

Lesson 1 of 8 ยท 6 min

The decision statement

If runs a block of code only when a condition is true. The condition is anything that evaluates to True or False, and the block always finishes with End If.

Sub CheckValue()
    Dim amount As Double
    amount = Range("B2").Value

    If amount > 1000 Then
        Range("C2").Value = "Large order"
    End If
End Sub

Adding alternatives

Else catches everything the condition missed. ElseIf adds further tests in between. VBA works down the list and runs the first branch that is true, then skips the rest โ€” so order matters:

Sub GradeOrder()
    Dim amount As Double
    amount = Range("B2").Value

    If amount > 10000 Then
        Range("C2").Value = "Key account"
    ElseIf amount > 1000 Then
        Range("C2").Value = "Large"
    ElseIf amount > 0 Then
        Range("C2").Value = "Standard"
    Else
        Range("C2").Value = "Empty or negative"
    End If
End Sub

Why order matters

Put amount > 0 first in that list and every order on earth would be labelled Standard, because the first true test wins and nothing below it is even looked at. Arrange your conditions from the most specific to the most general.

The one-line form

A short If with no Else can go on a single line, and then it needs no End If. Keep it for genuinely short statements โ€” anything longer belongs in a block:

If IsEmpty(Range("A1").Value) Then MsgBox "A1 is empty"

Booleans need no comparison

A Boolean variable is already True or False, so writing If isDone = True Then is redundant. If isDone Then says the same thing, and If Not isDone Then handles the opposite case.

Dim hasErrors As Boolean
hasErrors = (Range("D1").Value > 0)

If hasErrors Then
    MsgBox "Check the error column."
End If

Nesting

An If can contain another If. Indent each level by a further four spaces and the structure stays readable. Once you find yourself three levels deep, though, stop and ask whether the tests could be joined with And or flattened into a Select Case โ€” deeply nested Ifs are where logic bugs prefer to hide.

๐Ÿ’ก Always indent the body of an If by four spaces. When you start nesting them, the indentation is what tells you which End If belongs where.
Knowledge check
In an If / ElseIf / Else chain, how many branches run?

Sign in to answer and track your progress.

Sign in
Continues in this course
  • ๐Ÿ”’ Building Conditions 6 min
  • ๐Ÿ”’ Select Case 6 min
  • ๐Ÿ”’ For ... Next 7 min
  • ๐Ÿ”’ For Each 6 min
  • ๐Ÿ”’ Do While and Do Until 7 min
  • ๐Ÿ”’ Exit, Guard Clauses and Skipping 6 min
  • ๐Ÿ”’ Nested Loops Over Rows and Columns 7 min

Pro unlocks these 7 lessons, the final exam and the certificate โ€” plus every other course.

Unlock all lessons