A VBScript IIf( ) Function

This Web-exclusive sidebar introduces another approach to conditional statements: the VBScript IIf( ) function. This user-defined function simulates the built-in IIf( ) function in Visual Basic for Applications (VBA).

Dino Esposito

August 31, 1999

1 Min Read
ITPro Today logo in a gray background | ITPro Today

In Visual Basic for Applications (VBA), you can use a direct function called IIf( ) to assign a value to a variable, depending on the evaluation of a Boolean expression.

Related: A VBScript Version of VBA's IIf Function

This function's syntax is

VarName = IIf(expr, truepart, falsepart)

This function is basically a one-line replacement for this If...Then...Else statement:

If expr Then   VarName = truepartElse   VarName = falsepartEnd If

VBScript doesn't have a built-in IIf( ) function. However, I've created a user-defined IIf( ) function:

Function IIf( expr, truepart, falsepart )   IIf = falsepart   If expr Then IIf = truepartEnd Function

Because the VBScript runtime will evaluate both falsepart and truepart before passing them to the function, both expressions must be valid, even if just one will execute. For example, the code

MyVar = IIf( True, 1, 1/0 )

always produces a division by zero error, even when you confine the incorrect expression (i.e., 1/0) to falsepart, which the VBScript runtime never executes. This situation occurs because you're using a function and the VBScript runtime needs to evaluate the arguments to pass in.

In this example, using the full If...Then...Else statement is better:
If True Then   VarName = 1Else   VarName = 1/0End If

When you use the full If...Then...Else statement, VBScript evaluates an expression only if it is going to execute that expression. Thus, VBScript never evaluates the incorrect 1/0 expression, and the code executes successfully.

Learn more:  Understanding VBScript: Statements

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like