Search code examples
vbscriptinputboxdo-loops

Do Until count using Inputbox never terminates


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?


Solution

  • 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.