The VBScript Network and Systems Administrator's Cafe

Oct 30 2008   12:00AM GMT

A new found bug in VBScript that causes if then statements to return wrong comparisons (or is it?)

Jerry Lees Jerry Lees Profile: Jerry Lees

In the past I’ve cautioned you on always initializing your variables and encouraged you to always declare your variable types, rather than using the default variant type in VBScript. I’ll be the first to admit I don’t follow my own advice in my examples! However, variants can be dangerous!

Recently I had a situation where if statements were returning completely not correct results and for the life of me I couldn’t figure it out! Here is an example that illustrates what was happening to me.

one = 1
two = 2
three = 3
OneBillion = 1000000000

MyVar = inputbox(“Enter a number”)If one < MyVar Then
     WScript.Echo (one & ” is lessthan ” & MyVar)
End If
If two < MyVar Then
     WScript.Echo (two & ” is lessthan ” & MyVar)
End If
If three < MyVar Then
     WScript.Echo (three & ” is lessthan ” & MyVar)
End If
If OneBillion < MyVar Then
     WScript.Echo (OneBillion & ” is lessthan ” & MyVar)
End If

The basis of the problem is that I was taking input from a file that was a number– however I was reading the file and it was coming into the script and being used as a string by the variant variable. I then was comparing it to a number and the comparisons were not working 100% correctly. Check it out by entering several numbers into the script. Try entering 0, 1, 2, 3, and 1000000001.

The moral of the story here is to always cast your varables as a specific type or use the cint() function to convert your variant varables to numbers before doing number comparisons with a literal number and a variant variable that is supposed to contain a number.

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: