devxlogo

Write concise code with the IIf function

Write concise code with the IIf function

Use IIf when setting a value based upon an expression. This works only in situations where you have two choices, based upon the result of a Boolean expression.

'long wayIf Var1 > Var2 Then   Var3 = Var1 / Var2Else   Var3 = Var2 / Var1End If'this is more conciseVar3 = IIf(Var1 > Var2, Var1 / Var2, Var2 / Var1)

The IIf function is often useful to evaluate the minimum or the maximum of two numbers:

' the minimum of n1, n2min = IIf(n1 ' the maximum of n1, n2max = IIf(n1 >= n2, n1, n2)

Note, however, that the IIf syntax takes nearly 3 times as long to execute. Although it compacts the code, it should not be used in situations requiring many repetitions of the code. Moreover, IIf works ONLY in cases where all expressions execute correctly at run-time. In the above example, if either Var1 or Var2 is zero, the “short way” will always generate a run time error as all expressions on the line are evaluated.

devx-admin

Share the Post: