Controlling Loop in VBScript

Dim Greeting
Dim UserName
Dim TryAgain
Do
TryAgain = "No"
UserName = "InputBox("Please enter your name:")
If Trim(UserName) = " " Then
MsgBox "You must enter your name."
TryAgain = "Yes"
Else
Greeting = "Hello. " & UserName & ", it's a pleasure to meet you."
End If
Loop While TryAgain = "Yes"
MsgBox Greeting

We are using the TryAgain variable to control the loop. The loop starts at the word Do. At the End of the loop, if the TryAgaon variable equals "Yes", then the code starting at the word Do will execute again. Notice that at the top of the loop we initialize the TryAgain variable to "No". It is essential that this initialization take place inside the loop (that is, between the Do and Loop statements). This way the variable is re-initialized every time a loop occurs. If we did not do this, we would end up with what's called an infinite loop.

Infinite loops are undesirable, and whenever you code any kind of loop, you need to take measures to make sure they do not produce an infinite loop. As the term suggests, an infinite loop is one that never stops. Remember that the computer will only do what your script tells it to do. If you tell it to keep looking forever, it will. As long as the loop keeps looping, the code that comes after the loop never gets executed.

Let us move on to a line by line explanation of the code.

First
Next