Iif Function and ?: Operator

Returns one of two parts, depending on the evaluation of a condition.

Syntax

result = Iif(condition, truepart, falsepart)

result = (condition ? truepart : falsepart)

condition: boolean expression
truepart: Value or expression returned if condition is True.
falsepart: Value or expression returned if condition is False.

Description

The Iif function and ?: operator are synonymous and can be used as a shortcut for an If...Else statement. It is typically used as part of a larger expression where an If...Else statement would be awkward; however, both constructs have limitations (see Known Issues below). .

Example

Local greeting$ = "Good" + Iif( Hour(Now) > 17, " evening.", " day.")

Print greeting$

Or using the ?: operator:

Local greeting$ = "Good" + ( Hour(Now) > 17 ? " evening." : " day.")

Print greeting$

Both examples create a string containing "Good evening." if it is after 6pm. The equivalent code using an If...Else statement would look as follows:

Local greeting$ = "Good"

If Hour(Now) > 17

greeting += " evening."

Else

greeting += " day."

EndIf

Print greeting$

Known Issues

Using user-defined functions in the truepart and falsepart elements of this expression can sometime return an EdCodeGen error; use the If...Else construct if this occurs.
[Reported by James Gaite, 03/02/2015]

Alternatively, you could create a masking function to get around the problem like so:

Function  IifX(cond?, v1 As Variant, v2 As Variant)

Return Iif(cond?, v1, v2)

EndFunction

See Also

If…Else

{Created by Sjouke Hamstra; Last updated: 18/10/2017 by James Gaite}