Ways to code numeric conditional expressions

Often in our tips, we present a technique in which we wish to determine
if a function returns a number, any number, as its result. If it does,
then we want the condition to pass. If it doesn't, then we want the
condition to fail. For instance, to see if a textbox contains any text
whatsoever, we'd use:

If Len(Text1) Then

Or, to determine if our application raised an error, we'd code

If Err.Number Then

Inevitably, when we use such syntax, we receive a number of letters
stating that our code will never work as published--that the only
correct way to evaluate a function's numeric values is with expressions
such as:

If Len(Text1) <> 0 Then

Or

If Err.Number <> 0 Then

While the suggested comparison expressions work, they illustrate just
one of two ways to write conditions for Visual Basic. As stated in the
Help files with regard to conditions in a conditional statement, such
as If...Then:

"The condition is usually a comparison, but it can be any expression
that evaluates to a numeric value. Visual Basic interprets this value
as True or False; a zero numeric value is False, and any nonzero
numeric value is considered True."

With this in mind, then our simplified syntax might evaluate, like so

If Len("Abba") Then

If 4 Then

which passes the test, since 4, being a non-zero value, evaluates to True.

Where our simplified syntax can cause unintended results is when you
use the keyword Not in conjunction with it. For instance, given our
previous statement, it may seem as if the following code:

If Not Len(Text1) Then
     MsgBox "Empty"
End If

would display the message box only when the textbox is empty. In fact,
as is the code always displays the message.

This is because when evaluating the condition, Visual Basic applies
the Not first. When applied to numbers, the Not keyword reverses the
number's sign, and then adds -1 to it. So, continuing with our previous
example, the current code would evaluate like this:

If Not Len("Abba") Then

If Not 4 Then

If -5 Then

And as we pointed out, any value other than 0 evaluates to True so the
condition passes the test--as does 0, which the Not keyword converts
to -1, also True.

To avoid this behavior when using the Not keyword with the simplified
syntax, use the CBool() function to force VB to convert the number
into a Boolean value before applying the Not keyword, like so:

If Not CBool(Len(Text1)) Then

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.

“Nine people can't make a baby in a month.” - Fred Brooks