Reputation: 17
I am trying to get a Do Until loop to work in VBS. I ask the user for a number and then I want the script to Do Until the count is equal to the number the user entered.
number = InputBox("number")
count = 1
Do Until count = number
Wscript.Echo "count: " & count & VbCrLf &_
"number: " & number
count = count + 1
Loop
Wscript.Echo "Done." & VbCrLf &_
"count: " & count & VbCrLf &_
"number: " & number
When I run this, it continues to loop indefinitely rather than stopping after the count equals the number the user entered. If I hard code the number instead of asking for it, it works, but not when I have the user enter the number.
Can someone point out why this happens and how I can fix it?
Upvotes: 0
Views: 469
Reputation: 30153
Read VBScript Language Reference, Comparison Operators (VBScript):
If one expression is numeric and the other is a string then the numeric expression is less than the string expression.
count = 1
number = InputBox("number")
if IsNumeric( number) then number = CInt( number) else number = count
Do Until count >= number
Wscript.Echo "count: " & count & VbCrLf &_
"number: " & number
count = count + 1
Loop
Wscript.Echo "Done." & VbCrLf &_
"count: " & count & VbCrLf &_
"number: " & number
Note a change made from =
comparison to >=
in the Do Until count >= number
.
Upvotes: 2
Reputation: 46710
InputBox
is returning a string. You are comparing a string to a number which never matches hence the loop. Consider the following change.
number = Int(InputBox("number"))
count = 1
Do Until count = number
Wscript.Echo "count: " & count & VbCrLf & "number: " & number
count = count + 1
Loop
I am doing no data validation with this. Just trying to show you the issue. We cast the result of the InputBox
to int
then the loop condition works as expected.
Upvotes: 0