Try running the codes yourself for practice.
Table of Contents
The ‘Do Loop’
Today we are going to talk about Do Loops in VbScript; which loops or repeats something until a condition is satisfied.
Do msgbox "hello" Loop
Here the message box will continue to run a Message Box after you close the Message Box.
then then the same and so on without stop….
The only way to close the message box is by ending the task on Task Manager; specifically the program wscript.exe.
To exit the Loop, you use exit do:
Do msgbox "hello" exit do Loop
The script exits the loop the first time it runs. So once you close the message box, the VbScript exits the loop and continues the script after the loop.
Differently, you can use wscript.quit:
Do msgbox "hello" wscript.quit Loop
When you use wscript.quit, you are not only quitting the loop, but you are quitting the VbScript itself.
So if you have something after the Do Loop, wscript.quit does not allow the VbScript to run it; but forces the VbScript to quit. ie:
Do msgbox "hello" wscript.quit Loop msgbox "second"
But if you use exit do, then the script continues:
Do msgbox "hello" exit do Loop msgbox "second"
Exiting Loop by Condition
Example 1:: So set a condition to break the loop:
Option Explicit Dim a a=1 Do until a=5 a=a+1 msgbox a Loop
Option Explicit Dim a a=1 Do a=a+1 msgbox a Loop until a=5
Example2:: Another example of breaking Do Loop by condition:
Option Explicit Dim a a=1 Do until a>4 a=a+1 msgbox a Loop
*For the Loop to break, a has to be greater than 4.
Option Explicit Dim a a=1 Do while a<6 a=a+1 msgbox a Loop
a=0 → 0+1=1 → a=1 → 1+1=2 → a=2 →… a=7 → Break Loop
Option Explicit Dim pass Do until pass="wired" pass=inputbox("Password") Loop
Option Explicit Dim pass Do while pass<>"wired" pass=inputbox("Password") Loop
Do until pass="wired"
Do while pass<>"wired"
are the exact same command.
Example5:: Using If Then Statements to set up Break Loop Condition:
Option Explicit Dim pass Do pass=InputBox("Password") If pass="wired" then exit do End If Loop
Output: So the VbScript only exits the loop if the pass = wired. Otherwise, the VbScript loops back.
A more extensive version of Example5::
Option Explicit Dim pass Do pass=InputBox("Password") If pass="wired" then exit do ElseIf pass="" then msgbox "Don't leave field blank." ElseIf pass <> "wired" then msgbox "incorrect",vbcritical End If Loop