O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Miscellaneous Functions and Statements

The Immediate If function

The Immediate If function has the syntax:

IIf(Expression, TruePart, FalsePart)

If Expression is True, then the function returns TruePart. If Expression is False, the function returns FalsePart. 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 TruePart and FalsePart, 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 returns 1/x only when x is not equal to 0, the expression 1/x is evaluated in all cases, including when x = 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 exprx and valuex are 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required