Question : Does Excel VBA have a ternary conditional operator?
Can I do the same thing in Excel VBA than in the example of c++ code below?
This is called the ternary operator or also conditional assignment.
I know it exists on most languages.
If it doesn’t exist, can you make your own function, like the one I tried (but does not work) in the code snippet below?
In c++ you can write for example:
a = (b > 5) ? 2 : 0;
My own try in VBA to have a ternary-style function with embedded if-then-else:
Function ife(condition, then_, else_)
If (condition) Then
ife = then_
ife = else_
Solution: Does Excel VBA have a ternary conditional operator?
note that IIf is a function
From Excel VBA Help:
Returns one of two parts, depending on the evaluation of an expression.
IIf(expr, truepart, falsepart)
The IIf function syntax has these named arguments:
expr Required. Expression you want to evaluate.
truepart Required. Value or expression returned if expr is True.
falsepart Required. Value or expression returned if expr is False.
IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True.