Skip to main content

Conditional Operator in VBA/VB .NET

For most of C-like programming languages, conditional (ternary) operator is more concise than If statement. And it is also available in VBA and VB .NET.

VBA Conditional Operator

The function "IIF" exists since VB6, syntax seems like below:

Dim i As Integer
Dim s As String

i = 1
s = IIf(i > 0, "Greater than zero", "Zero or less than zero")

Debug.Print (s)
'Greater than zero

i = -1
s = IIf(i > 0, "Greater than zero", "Zero or less than zero")

Debug.Print (s)
'Zero or less than zero

It is convenient but need to notice that IIF will always evaluate all arguments. See below example:

Dim i As Integer

i = IIf(True, 1 + 1, 1*1)
'This is OK

i = IIf(True, 1 + 1, 1 / 0)
'This will throw exception due to division by zero

VB .NET Conditional Operator

To improve IIF problem, there is IF operator in VB .NET.

Dim i As Integer = 1
Dim s As String = If(i > 0, "Greater than zero", "Zero or less than zero")

Debug.Print(s)
'Greater than zero

i = -1
s = If(i > 0, "Greater than zero", "Zero or less than zero")

Debug.Print(s)
'Zero or less than zero

The syntax is similar, but the result will be only evaluated with the Boolean expression.

Dim i As Integer = If(True, 1 + 1, 1 / 0)
'This is OK because only evaluate 1+1


References:
IIf Function
If Operator (Visual Basic) | Microsoft Docs

Comments