The Excel VBA IIf function returns one of two values based on a condition, acting as a compact inline alternative to a full If...Then...Else block. Its syntax is IIf(expr, truepart, falsepart), where expr is evaluated as True or False, and the function returns truepart if True, otherwise falsepart. Unlike a worksheet IF, VBA’s IIf always evaluates both parts, which can cause unexpected errors if one part contains a division by zero or a function call.
What Is the VBA IIF Function and When Was It Added?
The IIf function has been part of VBA since the early days of Visual Basic for Applications, available in all modern versions including Excel 2016, 2019, 2021, and Microsoft 365. It is not a worksheet function; you use it inside VBA code, not in a cell. The name stands for “Immediate If” and it mirrors the ternary operator found in languages like C# (? :) or Python’s conditional expression (a if cond else b).
In practice, IIf is used for quick assignments, building strings conditionally, or setting property values in one line. For example, to set a cell’s value based on whether a number is positive:
Dim num As Long
num = 5
Range("A1").Value = IIf(num > 0, "Positive", "Non-positive")
This returns “Positive” because the condition is True. The function works with any data type—strings, numbers, dates, objects—as long as both parts are compatible or can be implicitly converted.
How the IIF Function Works: Syntax and Evaluation Order
The syntax is straightforward:
IIf(expr, truepart, falsepart)
expr– any expression that evaluates to a Boolean (True or False). If it’s a number, 0 is False and any non-zero is True.truepart– the value returned ifexpris True.falsepart– the value returned ifexpris False.
The critical detail is that VBA evaluates both truepart and falsepart before deciding which to return. This is different from a worksheet IF function, which only evaluates the branch it needs. For example, consider this code:
Dim x As Long
x = 10
MsgBox IIf(x > 5, 100 / x, 100 / (x - 10))
Even though x > 5 is True, VBA still evaluates 100 / (x - 10), which is a division by zero, causing a runtime error. This is the most common pitfall. To avoid it, use a regular If...Then...Else block when one branch could cause an error.
Practical Examples of Using IIF in Real Code
Here are a few concrete scenarios where IIf shines:
- Assigning a status label:
status = IIf(score >= 60, "Pass", "Fail") - Setting a cell’s background color conditionally:
Range("A1").Interior.Color = IIf(value < 0, vbRed, vbGreen) - Building a message with a variable part:
MsgBox IIf(isAdmin, "Welcome, Admin", "Welcome, User") - Handling empty strings:
name = IIf(Trim(cell.Value) = "", "N/A", cell.Value)
Note that IIf can also be nested, but readability suffers quickly. For example, IIf(a > b, IIf(a > c, "a", "c"), IIf(b > c, "b", "c")) finds the largest of three numbers, but a nested If or a Select Case is clearer.
IIF vs. If…Then…Else: How to Choose
Use IIf when you need a simple, one-line assignment and both branches are safe to evaluate. Use a full If...Then...Else block when:
- One branch could cause an error (division by zero, invalid object reference).
- You need to execute multiple statements per branch.
- You need to use
ElseIffor more than two outcomes. - Performance is critical in a loop—
IIfis slightly slower because it evaluates both branches.
For example, the following is safer than the earlier division example:
Dim result As Double
If x <> 0 Then
result = 100 / x
Else
result = 0
End If
This only divides when x is non-zero.
Common Problems and Misconceptions with IIF
Beyond the evaluation issue, there are several other gotchas:
- Data type coercion: If
truepartis a string andfalsepartis a number, VBA may convert the number to a string, or raise a type mismatch if the conversion isn’t possible. For example,IIf(True, "Text", 123)returns “Text” butIIf(False, "Text", 123)returns “123” as a string, not a number. - Null handling: If either part is
Null, the result isNullunless you useNz(in Access) or handle it explicitly. In Excel VBA,Nullpropagates. - Object references: If a branch returns an object, the other branch must also return an object or
Nothing, otherwise you get a type mismatch. - Performance in loops: In a loop of 100,000 iterations, evaluating both branches can double the work. Use
Iffor speed. - Misunderstanding with worksheet IF: Some users try to use
IIfin a cell formula and get a #NAME? error. That’s because it’s VBA-only.
IIF vs. CHOOSE and SELECT CASE: Alternatives
If you have more than two conditions, IIf becomes unwieldy. Alternatives include:
Select Case– best for multiple discrete values or ranges.Choose(index, choice1, choice2, ...)– picks from a list based on an index (1-based).- Worksheet
IFfunction – if you’re writing a formula in a cell, use=IF(condition, true, false)in the worksheet, not VBA.
For example, to assign a letter grade:
Dim grade As String
grade = Choose(score \ 10 + 1, "F", "F", "F", "F", "F", "D", "C", "B", "A", "A", "A")
But Select Case is clearer:
Select Case score
Case Is >= 90: grade = "A"
Case Is >= 80: grade = "B"
Case Is >= 70: grade = "C"
Case Is >= 60: grade = "D"
Case Else: grade = "F"
End Select
Frequently Asked Questions
Can I use IIF in a worksheet cell?
No. IIf is a VBA function, not a worksheet function. In a cell, use =IF(condition, true, false). To call VBA from a cell, you’d need a user-defined function (UDF) that wraps IIf.
Why does my IIF give a division by zero error even when the condition is false?
Because VBA evaluates both truepart and falsepart before deciding. If either contains an error, it occurs. Use a regular If block to avoid this.
Can IIF return an empty string or Nothing?
Yes. Use IIf(condition, "", "something") for empty string, or IIf(condition, Nothing, obj) for objects, but be careful with type mismatches.
Is IIF faster than If…Then…Else?
No, it’s slightly slower because it evaluates both branches. For most code the difference is negligible, but in tight loops, use If.
How do I nest IIF functions?
You can nest them, but it’s hard to read. Example: IIf(a>b, IIf(a>c, "a", "c"), IIf(b>c, "b", "c")). For clarity, use Select Case or nested If.
Does IIF work with dates and ranges?
Yes, it works with any data type. For ranges, you’d return the range object, but remember both branches are evaluated, so if one branch refers to a non-existent sheet, it errors.
Safety and Best Practices When Using IIF
When writing macros that use IIf, always save a copy of your workbook before running, because macros cannot be undone with Ctrl+Z. Here are additional best practices:
- Always declare variables with explicit types to avoid coercion surprises.
- Test both branches mentally for potential errors before using
IIf. - If a branch calls a function that has side effects (like modifying a cell), remember that function will run even if its branch isn’t returned.
- Use line continuation (space underscore) to keep long
IIfstatements readable.
For example, a safe way to avoid division by zero:
Dim safeResult As Double
If x <> 0 Then
safeResult = 100 / x
Else
safeResult = 0
End If
This is always preferable to IIf(x <> 0, 100 / x, 0) because the false branch is evaluated even when x is zero, causing an error.
Related
- Cell Counting Protocol: Step-by-Step Guide
- Minimize Window Shortcut: Windows & Mac Keys
- How to Calculate Subtotal in Google Sheets
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Cannot Run a Macro in Excel? Fix Common CausesIf you cannot run a macro in Excel, first confirm that the workbook is saved in a macro-capable…
- Excel VBA: How to Check AutoFilter StatusIn Excel VBA, check Worksheet.FilterMode to find out whether a worksheet currently has a filter applied, and check…
- Macro Cazador WoW: Best Macros for HunterIn World of Warcraft, a “macro cazador” (Spanish for “hunter macro”) is a custom command that lets a…
- Pivot Table Not Refreshing Through VBA? Causes and FixesIf an Excel PivotTable does not update through VBA, first confirm that its source includes the changed rows,…
- Excel Macro Text to Columns: VBA Setup and ExamplesTo run Excel’s Text to Columns tool with a macro, select the text column, then use VBA’s Range.TextToColumns…
- Outlook Macros: How to Enable Them Safely in Classic OutlookTo enable VBA macros in classic Outlook for Windows, open File > Options > Trust Center > Trust…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.