The VBA If...ElseIf...Else statement runs one block of code when a condition is true, and optionally tests additional conditions in order. It is the core way to make decisions in Excel macros, and its full syntax is If condition1 Then ... ElseIf condition2 Then ... Else ... End If.
What Is the If ElseIf Statement For?
In Excel VBA, you often need to check a cell value, a variable, or a calculated result and then do different things depending on that value. The If statement is the simplest branching tool. When you have more than two possible outcomes, ElseIf lets you chain multiple checks without nesting If blocks inside each other, which keeps the code readable.
For example, a macro that assigns a letter grade to a numeric score could use If and ElseIf to avoid writing four separate If blocks. The statement evaluates each condition from top to bottom and stops at the first one that is True. If none are true, the Else block runs (if you include it).
Full Syntax and How It Works
The formal syntax in the VBA language reference is:
If condition1 Then
' statements if condition1 is True
ElseIf condition2 Then
' statements if condition2 is True
ElseIf condition3 Then
' statements if condition3 is True
Else
' statements if none of the above are True
End If
Key rules:
Thenis required after each condition, butElseIfandElseare optional.- You can have as many
ElseIflines as you need, but each one is evaluated only if all previous conditions wereFalse. - The entire block must end with
End If. Forgetting it is a common compile error. - Conditions are usually comparisons like
x > 10,Range("A1").Value = "Yes", orIsEmpty(Cells(1,1)). You can also use logical operatorsAnd,Or, andNot.
Here is a concrete example that checks a numeric score and returns a letter grade:
Sub GradeExample()
Dim score As Integer
Dim grade As String
score = Range("B2").Value
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
ElseIf score >= 70 Then
grade = "C"
ElseIf score >= 60 Then
grade = "D"
Else
grade = "F"
End If
Range("C2").Value = grade
End Sub
Notice that the order matters: score >= 90 is checked first, so a score of 95 never reaches the second condition. This is the intended behavior.
Single-Line If vs. Block If
VBA also allows a single-line form: If condition Then statement. That is fine for one short action, but it cannot contain multiple ElseIf branches cleanly. For anything beyond a single action, use the block form above. The block form is easier to read, supports comments, and avoids the common mistake of putting two statements on one line without a colon separator.
Example of single-line (acceptable for one quick check):
If Range("A1").Value = "" Then MsgBox "Cell is empty"
But if you need to test several conditions, always use the block form. Mixing the two can cause errors because the single-line form treats the entire line as one statement.
Choosing Between ElseIf, Select Case, and Nested If
When you have many conditions, you have three main options in VBA. Here is how to choose:
- ElseIf – best when conditions are not simple equality checks (e.g., ranges,
And/Orlogic) or when you have fewer than, say, five branches. - Select Case – best when you are comparing one expression to many specific values or ranges. It is cleaner and often faster to type. Example:
Select Case score Case Is >= 90: grade = "A" Case 80 To 89: grade = "B" End Select. - Nested If – used when a second decision depends on the result of the first, e.g., check if a cell is not empty, then check its value. Nesting is fine but can become hard to read; consider using
Andin a single condition if the logic is simple.
For most decision trees, ElseIf is the most straightforward. Use Select Case when you are testing the same variable against multiple discrete values or ranges.
Common Mistakes and How to Fix Them
Beginners often hit the same issues with If...ElseIf. Here are the most frequent ones:
- Forgetting
End If– the compiler will complain. Always close the block. - Using
ElseIfas two words – it is one word, no space.Else Ifis a separate nested structure and requires its ownEnd If. - Putting a condition after
Else–Elsehas no condition; it runs when all others fail. If you need another test, useElseIf. - Comparing strings with
=but forgetting case sensitivity – by default, VBA is case-insensitive, so"yes" = "YES"isTrue. If you need exact case, useStrCompwithvbBinaryCompare. - Testing
Rangevalues without checking for empty – an empty cell returns 0 when compared to a number, which can cause unexpected branches. UseIsEmptyfirst if needed. - Ordering conditions incorrectly – for example, testing
score >= 60beforescore >= 90would never let the 90 branch run. Always put the most restrictive conditions first.
Another common misconception: ElseIf does not evaluate all conditions. It stops at the first True. This is efficient and often exactly what you want, but if you need to check every condition independently, use separate If blocks.
Practical Example with Real Data
Suppose you have a list of sales amounts in column A (rows 2 to 100) and you want to add a commission rate in column B. The rules: 0–999 = 5%, 1000–4999 = 7%, 5000+ = 10%. Here is a macro that loops through the rows and uses ElseIf:
Sub ApplyCommission()
Dim i As Long
Dim lastRow As Long
Dim sales As Double
Dim rate As Double
' Find last used row in column A
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastRow
sales = Cells(i, 1).Value
If sales < 1000 Then
rate = 0.05
ElseIf sales < 5000 Then
rate = 0.07
Else
rate = 0.1
End If
Cells(i, 2).Value = rate
Next i
End Sub
This example shows how ElseIf works inside a loop. The conditions are mutually exclusive because the second condition is only reached when the first is false (i.e., sales is not < 1000).
Performance and Best Practices
For typical macros with a few hundred rows, ElseIf is plenty fast. But if you are processing tens of thousands of rows, consider these tips:
- Read the data into an array first, then loop through the array, rather than reading each cell individually. This is much faster.
- Use
Select Casewhen you have many discrete values; it can be slightly faster and is more readable. - Turn off screen updating with
Application.ScreenUpdating = Falseat the start and set it back toTrueat the end, especially when writing values to cells. - Avoid deeply nested
Ifblocks; refactor into separate functions if the logic becomes complex.
Always save a copy of your workbook before running any macro, because macros cannot be undone with Ctrl+Z. If your macro modifies data, test it on a backup first.
Frequently Asked Questions
Can I use multiple statements inside an If block?
Yes, you can put as many lines as you want between Then and ElseIf or Else. They all run if that branch is taken. Just make sure each statement is on its own line (or separated by colons) and the block ends with End If.
What is the difference between ElseIf and Else If?
ElseIf is a single keyword in VBA. Else If (with a space) is actually a nested If statement inside an Else block, which requires its own End If. Using Else If is valid but adds an extra End If and is generally harder to read. Stick with ElseIf unless you need a separate condition that depends on the first branch failing.
Does ElseIf evaluate all conditions?
No. VBA stops evaluating as soon as one condition is True. So if the first condition is true, the rest are not checked. This is efficient and means you can rely on the order of your conditions.
Can I use ElseIf without an Else?
Yes, Else is optional. If no condition is true and there is no Else, the macro simply continues after End If without running any code from that block.
How do I check if a cell is empty before using ElseIf?
Use IsEmpty or compare to an empty string. For example: If IsEmpty(Range("A1")) Then ... ElseIf Range("A1").Value = "" Then .... Note that a cell containing a formula that returns “” is not truly empty, so IsEmpty will be False; you may need to check Len(Range("A1").Value) = 0.
What is the keyboard shortcut to run a macro?
You can press F5 in the VBA editor to run the current macro, or Alt+F8 in Excel to open the Macro dialog and run from there. On a Mac, use Fn+F5 or Option+F8 respectively.
Related
- C Battery Diameter: Exact Size in mm and Inches
- Balloon Columns with Numbers? Meaning & Use
- All PC Shortcuts? The Complete List You Need
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Replace Excel VBA: Best Alternatives and When to SwitchYes, you can replace Excel VBA, but there is no single substitute that fits every macro. For repeatable…
- VBA Hide UserForm: Methods, Code, and When to Use ThemTo hide an Excel VBA UserForm without unloading it, call Me.Hide from code inside the form. The form…
- VBA Dictionary: Search by Key and Check Whether It ExistsTo search a VBA Dictionary by key, call its Exists method before retrieving the value: use If dict.Exists(searchKey)…
- Excel VBA Evaluate: How It Works and When to Use ItIn Excel VBA, Application.Evaluate interprets a text expression using Excel’s formula language and returns the result as a…
- Excel Macro to Protect a Sheet: VBA Code and SetupTo protect an Excel worksheet with a macro, call the sheet’s VBA Protect method, for example Worksheets("Entry").Protect Password:="change-me".…
- Excel VBA: Get a PivotTable NameIn Excel VBA, get a PivotTable’s name from its Name property: pt.Name. First obtain the PivotTable object from…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.