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 <= n2, n1, n2)' 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.

See also  Is Machine Learning Automating Creativity in Graphic Design?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist