Create an IIF statement in VBScript

Many ASP developers are also Visual Basic developers, and as such, we often have to shift gears between the two, remembering (or trying to remember, at least) which features exist in one and not the other. Differences in error trapping and class definitions are among the more well-recognized, but there are many more subtle discrepancies. For example, VB has a handy function, IIf, which allows you to collapse several lines of Boolean logic into a single expression, like this:

blnFoo1 = True
blnFoo2 = False
MsgBox IIf(blnFoo1 = blnFoo2, "The same!", "Different!")

As you can see, the first parameter represents the expression to evaluate. The second parameter is the result to return if the expression evaluates to True, while the third parameter is the result to return if the expression evaluates to False. VBScript, unfortunately, doesn't support this function, but you can easily write your own equivalent, like this:

Public Function IIf(blnExpression, vTrueResult, vFalseResult)
  If blnExpression Then
    IIf = vTrueResult
  Else
    IIf = vFalseResult
  End If
End Function

You might also like...

Comments

ElementK Journals

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity.” - Dennis Ritchie