Visual Basic provides several different structures for repeating sets of instructions (looping) in programs.

There are a number of different styles of loop, each suited best to certain situations.  We looked at the For...Next loop in the die rolling example.  The For...Next loop is most suitable when you know exactly the number of times you want to loop.  A Do While loop is more useful if you want to keep looping until a certain condition becomes True (or False)

Do While Loop

A Do while loop might look like this:

Do While shopkeeper is not looking

       Eat lolly

Loop

When the computer sees a Do While loop, it works out whether the condition (shopkeeper is not looking) is true or false.

If the condition is true, it follows the instructions (Eat lolly)

If, or when, the condition is false, (ie shopkeeper is looking) then it will ignore all the instructions in the loop and move on in the program.

So lollies will be eaten until the shopkeeper looks, then no more will be eaten!

Look carefully at this code:

Sub askName()

userName=""

userName = InputBox(prompt:="What is your name?", Title:="Input Name")

Do While userName=""

userName = InputBox(prompt:="Please type your name!", _
Title:="Input Name")

Loop

End Sub

 

 

The first line deletes any information stored in userName. The purpose of the loop (in bold) is to ensure that the user has entered a name.  While the userName is blank, (ie until the user enters a name) the computer will keep popping up an Input Box asking for a name.

You could also add in this line inside your loop:  

Beep

This would play a system Beep if the user has not entered in a name.

Write a procedure of your own that uses a do while loop.