That's not how the IIf
function works.
It's a function, not a statement: you use its return value like you would with any other function - using it for control flow is a bad idea.
At a glance, IIf
works a little bit like the ternary operator does in other languages:
string result = (foo == 0 ? "Zero" : "NonZero");
Condition, value if true, value if false, and both possible values are of the same type.
It's for turning this:
If foo = 0
Debug.Print "Zero"
Else
Debug.Print "NonZero"
End If
Into this:
Debug.Print IIf(foo = 0, "Zero", "NonZero")
Be careful though, IIf
evaluates both the true and the false parts, so you will not want to have side-effects there. For example, calling the below Foo
procedure:
Public Sub Foo()
Debug.Print IIf(IsNumeric(42), A, B)
End Sub
Private Function A() As String
Debug.Print "in A"
A = "A"
End Function
Private Function B() As String
Debug.Print "in B"
B = "B"
End Function
Results in this output:
in A
in B
A
That's why using IIf
for control flow isn't ideal. But when the true result and false result arguments are constant expressions, if used judiciously, it can help improve your code's readability by turning If...Else...End If
blocks into a simple function call.
Like all good things, best not abuse it.