0

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?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Jono
  • 17
  • 5

2 Answers2

2

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.

JosefZ
  • 28,460
  • 5
  • 44
  • 83
  • Both of these answers (JosefZ and Matt) are helpful, especially in pointing out that the user's input is seen as a string instead of an integer. I did consider that, but when I included the `IsNumeric` in the Wscript.Echo statement before, it came back as True. I now understand that IsNumeric doesn't mean Integer. I was also confused by the fact that in my experimentation, using `For...Next` instead of `Do...Loop` worked. Anyway, I've altered my code per JosefZ's suggestion and it works great. Thanks! – Jono Mar 26 '15 at 15:20
0

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.

Matt
  • 45,022
  • 8
  • 78
  • 119