TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Language: VB4,VB5,VB6,VBS
Expertise: beginner
Oct 16, 1999

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# 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 way
If Var1 > Var2 Then
Var3 = Var1 / Var2
Else
Var3 = Var2 / Var1
End If

'this is more concise
Var3 = 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, n2
min = IIf(n1 <= n2, n1, n2)

' the maximum of n1, n2
max = 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.
Bryan Fazekas

 Submit a Tip Browse "XML" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date