7. VbScript | Do Loop

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.

For example:

Do
msgbox "hello"
Loop

Output:

Here the message box will continue to run a Message Box after you close the Message Box.

6 then 6 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.

7

Exiting Loop

To exit the Loop, you use exit do:

Do
msgbox "hello"
exit do
Loop

Output:

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

Output:

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"

Output:

only

6

But if you use exit do, then the script continues:

Do
msgbox "hello"
exit do
Loop

msgbox "second"

Output:

6 and then 8

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

Or

Option Explicit
Dim a

a=1

Do 
a=a+1
msgbox a
Loop until a=5

Output:

55


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.

Output:

55


Example3::

Option Explicit
Dim a

a=1

Do while a<6
a=a+1
msgbox a
Loop

Output:

a=0 → 0+1=1 → a=1 → 1+1=2 → a=2 →… a=7 → Break Loop


Example4::

Option Explicit
Dim pass

Do until pass="wired"
pass=inputbox("Password")
Loop

Or

Option Explicit
Dim pass

Do while pass<>"wired"
pass=inputbox("Password")
Loop

Output:

56

*Notice that

Do until pass="wired"

and

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

Output:

57


What's Your Opinion?