In VBA, If...Then...ElseIf is a conditional statement that lets you test multiple conditions in sequence, executing only the block of code belonging to the first condition that evaluates to True. You use it when you have more than two possible outcomes and want to avoid deeply nested If statements.
What Is If Then ElseIf and When Do You Need It?
VBA’s If statement is the backbone of decision-making in macros. The simplest form is a single-line If...Then, but when you need to check several mutually exclusive conditions, ElseIf gives you a cleaner alternative to nesting multiple If blocks inside each other. For example, a grading macro that assigns A, B, C, or F based on a score naturally fits ElseIf.
Without ElseIf, you would write:
If score >= 90 Then
grade = "A"
Else
If score >= 80 Then
grade = "B"
Else
If score >= 70 Then
grade = "C"
Else
grade = "F"
End If
End If
End If
That works, but it is hard to read and easy to misplace an End If. The ElseIf version flattens the logic and is the standard way to handle multiple branches.
Syntax and Structure of ElseIf
The full syntax is:
If condition1 Then
' statements if condition1 is True
ElseIf condition2 Then
' statements if condition1 is False and condition2 is True
ElseIf condition3 Then
' statements if both previous are False and condition3 is True
Else
' statements if none of the above are True
End If
Key rules:
- You can have as many
ElseIfblocks as you need, but each condition is evaluated only if all previous ones wereFalse. - The
Elseblock is optional and runs if every condition isFalse. - Each
Ifmust end with a matchingEnd If—unless you use the single-line form withoutElseIf. - Conditions can be any expression that returns a Boolean (
TrueorFalse), including comparisons,And/Orlogic, or function calls.
Here is a concrete example that checks a cell value and writes a message:
Sub CheckValue()
Dim val As Double
val = Range("A1").Value
If val > 100 Then
MsgBox "Over 100"
ElseIf val > 50 Then
MsgBox "Between 51 and 100"
ElseIf val > 0 Then
MsgBox "Between 1 and 50"
Else
MsgBox "Zero or negative"
End If
End Sub
Note that the order matters: if val is 75, the first condition (>100) is False, the second (>50) is True, so it prints “Between 51 and 100” and skips the rest.
How to Choose Between ElseIf, Select Case, and Nested If
Three common ways to handle multiple conditions exist, and each fits different situations:
- If…ElseIf: Best when conditions are not simple equality checks, or when you need to test different variables in each branch (e.g.,
If x > 5 Then... ElseIf y < 0 Then...). - Select Case: Cleaner when you are comparing one expression against several possible values or ranges (e.g.,
Select Case grade). It is often more readable and slightly faster for many branches. - Nested If: Use when you need to check a second condition only after a first one is true (e.g.,
If x > 0 Then If y > 0 Then). This is a different logical structure, not just a style choice.
As a rule of thumb, if you find yourself writing more than three ElseIf blocks, consider Select Case. For example, the grading macro is better with Select Case:
Select Case score
Case Is >= 90
grade = "A"
Case Is >= 80
grade = "B"
Case Is >= 70
grade = "C"
Case Else
grade = "F"
End Select
But ElseIf is the right tool when conditions involve different variables or complex Boolean expressions.
Common Mistakes and How to Avoid Them
Even experienced VBA developers trip over these pitfalls:
- Forgetting the space in
ElseIf: WritingElseIfas one word is correct;Else If(with a space) creates a nestedIfinside anElseblock, which changes the logic and requires an extraEnd If. - Missing
End If: EveryIfblock that spans multiple lines must end withEnd If. The compiler will error with “Block If without End If”. - Using
=instead of=in comparisons: In VBA,=is both assignment and equality, soIf x = 5 Thenis correct. But be careful with object comparisons—useIsfor objects, not=. - Ordering conditions incorrectly: Because
ElseIfstops at the firstTrue, put the most specific or restrictive conditions first. For example, if you checkIf x > 0beforeIf x > 10, the second branch will never run for values above 10. - Using
And/Orincorrectly: VBA usesAndandOr(not&&or||). Also, be aware of short-circuiting: VBA does not short-circuit, meaning all parts of anAndexpression are evaluated even if the first isFalse. This can cause errors if a later part references an invalid object.
Practical Example: Validating User Input
Imagine you have a macro that asks for a user’s age and categorizes them. Here is a full example with error handling:
Sub CategorizeAge()
Dim age As Variant
age = InputBox("Enter your age:")
' Check if input is numeric
If Not IsNumeric(age) Then
MsgBox "Please enter a number."
Exit Sub
End If
Dim ageNum As Integer
ageNum = CInt(age)
If ageNum < 0 Then
MsgBox "Age cannot be negative."
ElseIf ageNum < 13 Then
MsgBox "Child"
ElseIf ageNum < 20 Then
MsgBox "Teenager"
ElseIf ageNum < 65 Then
MsgBox "Adult"
Else
MsgBox "Senior"
End If
End Sub
Notice the Exit Sub after an error message—this prevents the rest of the code from running with invalid data. Also, the conditions are ordered from most restrictive (negative) to least, which is correct.
Performance and Readability Considerations
For most macros, the speed difference between ElseIf and Select Case is negligible. However, if you are looping through thousands of rows, every extra condition matters. Select Case is often slightly faster because it evaluates the test expression once, whereas ElseIf evaluates each condition separately. But the bigger cost is usually the loop itself, not the conditional.
Readability should be your primary guide. If you have more than three branches, Select Case is almost always clearer. If you have complex Boolean logic (e.g., If (a > 0 And b < 0) Or c = 5), If...ElseIf is the only option because Select Case cannot handle arbitrary expressions.
One more tip: avoid deeply nested If statements. If you find yourself three levels deep, refactor into separate functions or use Exit Sub/Exit Function to early-exit on error conditions. This is often called the “guard clause” pattern.
Frequently Asked Questions
What is the difference between ElseIf and Else If?
In VBA, ElseIf (one word) is the correct syntax for adding another condition to the same If block. Else If (two words) is not valid VBA—it is a common mistake from other languages. If you write Else If, VBA treats it as an Else block containing a new If statement, which requires an extra End If and changes the logic.
Can I use ElseIf without an Else?
Yes, the Else block is optional. If no condition is True and there is no Else, the macro simply skips the entire If block and continues with the next line after End If.
How many ElseIf blocks can I have?
There is no hard limit in VBA, but practical limits exist. Excel’s VBA compiler can handle hundreds of ElseIf blocks, but for maintainability, you should switch to Select Case or a lookup table (e.g., using Application.Match or a dictionary) when you exceed about five branches.
Does ElseIf evaluate all conditions or stop at the first True?
It stops at the first True. Once a condition evaluates to True, VBA executes that block and jumps to the line after End If. It does not evaluate subsequent ElseIf conditions. This is why ordering matters.
Can I use ElseIf in a single-line If?
No. The single-line form only supports If...Then...Else without ElseIf. For example, If x > 0 Then MsgBox "Positive" Else MsgBox "Non-positive" is valid, but you cannot add ElseIf on one line. You must use the multi-line block form.
What is the keyboard shortcut to run a macro with If Then ElseIf?
There is no specific shortcut for the statement itself. To run a macro, press F5 while in the VBA editor (or F5 on Mac as well). To step through line by line, press F8 (Windows) or Shift+Command+I (Mac) to open the Immediate window, but stepping is done with F8 on both platforms. Always save a copy of your workbook before running a macro, because macros cannot be undone with Ctrl+Z.
Related
- Why Is Maya Not Importing FBX? Fixes & Causes
- T Minus Two Months: Meaning, Origin & Real Uses
- How to Improve Aim on Mouse: 12 Proven Steps
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Progress Bar Without a UserForm: 3 MethodsYes. Excel VBA can show progress without a UserForm by updating Excel’s status bar, writing progress to a…
- Excel VBA MAX Function: How to Find the Largest ValueExcel VBA does not have a built-in Max function, but a macro can use Excel’s worksheet function through…
- VBA Dictionary Multiple Items per Key: Practical GuideYes. A VBA Scripting.Dictionary can hold multiple items for one key if you store a container—most often a…
- Excel VBA Mid Function: Syntax, Examples, and TipsIn Excel VBA, the Mid function returns part of a string, starting at a position you specify. Use…
- Excel VBA: How to Save a Backup Copy of a WorkbookTo save a backup copy of the workbook that contains your VBA code, use ThisWorkbook.SaveCopyAs fullPath. For example,…
- MS Access VBA Dictionary: Setup, Examples, and TipsYes. Microsoft Access VBA can use the Scripting.Dictionary object to store key-value pairs, look up a value by…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.