Miscellaneous Functions and Statements
- The Immediate If function
The Immediate If function has the syntax:
IIf(
Expression, TruePart, FalsePart)If
Expressionis True, then the function returnsTruePart. IfExpressionis False, the function returnsFalsePart. For instance, the following code displays a dialog box indicating whether the first paragraph in the active document is too long (that is, if it contains over 100 words):Dim cWords As Long cWords = ActiveDocument.Paragraphs(1).Range.Words.count MsgBox "First paragraph is " & _ IIf(cWords > 100, "too long", "not too long")It is very important to note that the Immediate If function (IIf) always evaluates both
TruePartandFalsePart, even though it returns only one of them. Hence, we must be careful about undesirable side effects. For example, the following code will produce a division-by-zero error because even though the IIf function returns1/xonly whenxis not equal to 0, the expression1/xis evaluated in all cases, including whenx= 0:x = 0 y = IIf(x = 0, x ^ 2, 1 / x)
- The Switch function
The syntax of the Switch function is:
Switch(
expr1, value1, expr2, value2, ... , exprn, valuen)where
exprxandvaluexare expressions. Note that there need be only one expression-value pair, but the function is more meaningful if there are at least two such pairs.The Switch function evaluates each expression
exprx. When it encounters the first True expression, it returns the corresponding value. As with the IIf function, Switch always evaluates ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access