Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 190
VBA's IIf function
ОглавлениеVBA offers an alternative to the If-Then construct: the IIf function. This function takes three arguments and works much like Excel's IF worksheet function. The syntax is as follows:
IIf(expr, truepart, falsepart)
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
The following instruction demonstrates the use of the IIf function. The message box displays Zero if cell A1 contains a 0 or is empty and displays Nonzero if cell A1 contains anything else.
MsgBox IIf(Range("A1") = 0, "Zero", "Nonzero")
It's important to understand that the third argument (falsepart) is always evaluated, even if the first argument (expr) is True. Therefore, the following statement generates a division-by-zero error if the value of n is 0 (zero):
MsgBox IIf(n = 0, 0, 1 / n)