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 = truepart
Else
   VarName = falsepart
End 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 = truepart
End 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 = 1
Else
   VarName = 1/0
End 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