The IIf function

Have you come across the IIf function? This is what help says:

Syntax

IIf(expr, truepart, falsepart)

The IIf function syntax has these named arguments:

Part Description
expr Required. Expression you want to evaluate.
truepart Required. Value or expression returned if expr is True.
falsepart Required. Value or expression returned if expr is False.

Then you would use it as follows:

MsgBox "Hello " & IIf(strName="John", _
"John", "some one else") & ". How are you?", vbOK

This is a very mundane example, but you get the idea: it can save a lot of code if you
just want to evaluate something little. Did you know that it is part of the VBA DLL? This
means that if you are only writing a small prgram that does not use anything else from the
VBA library then you could cut out this DLL. This is how:

Public Function IIf2(arg As Boolean, _
ret1 As Variant, ret2 As Variant) As Variant
If arg Then
    IIf2 = ret1
Else
    IIf2 = ret2
End If
End Function

Latest Posts

Related Stories