VBA Function: IIf

The VBA IIf function returns one of the two values passed as arguments based on a condition.

It is somewhat equivalent to the =IF(...) function in VBA.


IIf(condition, value_if_true, value_if_false)

Example of Usage

To return a value based on a condition, an If statement is commonly used:

Sub example()
    grade = 14
    If grade >= 15 Then
        MsgBox "Congratulations!"
        MsgBox "Meh..."
    End If
End Sub

The IIf function simplifies this code by condensing the condition into a single line:

Sub example()
    grade = 14
    MsgBox IIf(grade >= 15, "Congratulations!", "Meh...")
End Sub