Ternary Operator in VBA

 From https://www.excel-pratique.com/en/vba_tricks/ternary-operator

Ternary Operator in VBA?

Most programming languages have a ternary operator (which allows writing a condition in a simple way on a single line), usually in the following form:

my_condition ? if_true : if_false

Unfortunately, this operator does not exist in VBA, but there is a function that comes close and allows writing a condition on a single line.

That function is called IIf.

SIMPLE EXAMPLE 1

To better understand, here is a simple If condition:

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

Using the IIf function, you can simplify the code like this:

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

End Sub

SIMPLE EXAMPLE 2

This is the same condition as before, but this time displaying the result in a MsgBox:

Sub condition()
    
    age = 20
    
    If age >= 18 Then
        myText = "an adult"
    Else
        myText = "a minor"
    End If
    
    MsgBox "John is " & myText & "!"
    
End Sub

Using the IIf function here allows for even further simplification by directly adding the condition within the MsgBox value:

Sub condition()
    
    age = 20

    MsgBox "John is " & IIf(age >= 18, "an adult", "a minor") & "!"
    
End Sub

Comments

Popular posts from this blog

Add GitHub Repository to DBeaver CE Secured with SSH Protocol

Keyboard Shortcut to "Toggle Line Comments" in DBeaver

DBeaver Shortcuts