Ternary Operator in VBA?

Most programming languages have a ternary operator (which allows a condition to be written on a single line), usually in the following form:

condition ? if_true : if_false

Unfortunately, this operator does not exist in VBA but there's a similar function which allows you to write a condition on a line.

It's the IIf function.


Example

To illustrate, here's a simple If condition:

Sub condition()
    
    age = 20
    
    If age >= 18 Then
        result = "adult"
    Else
        result = "minor"
    End If
    
End Sub

Using the IIf function, you can simplify the entry as follows:

Sub condition()
    
    age = 20
    
    result = IIf(age >= 18, "adult", "minor")

End Sub