The Do Until Loop

Whereas the Do While loop continues executing the body of the loop as long as the comparison test is true, the Do Until loop executes the body of the loop as long as the comparison test is false. The program's logic at the time of the loop determines which kind of loop works best in a given situation.

Do Until works almost exactly like the Do While loop except that the Do Until loop continues executing the body of the loop until the comparison test is true. Like the Do While, the Do Until is a multiline looping statement that can execute a block of code that's one or more lines long.

Here is the format of Do Until:

Do Until (comparison test)

Block of one or more Visual Basic statements

Loop

tip

Remember that the comparison test must be false for the loop to continue.

You can use the Do While or the Do Until for almost any loop. Listing 8.2 contains the age-checking event procedure that contains a Do Until loop. The loop ensures that the age falls between two values. As you can see, comparison test for the Do Until is the opposite of that used in Listing 8.1's Do While loop.

sidebar

Which Loop Is Best?

Use the loop that makes for the cleanest and clearest comparison test. Sometimes, the logic makes the Do While clearer, whereas other loops seem to work better when you set them up with Do Until.

Do Until continues executing a block of Visual Basic statements as long as comparison test is false. As soon as comparison test becomes true (the loop is said to Do a loop until the condition becomes false), the loop terminates and the program continues on the line that follows the closing loop statement.

There is really no technical advantage to using Do While or Do Until. Use whichever one seems to flow the best for any given application.

Listing 8.2. The Do Until loops until comparison test becomes true.

1: Dim strAge As String

2: Dim intAge As Integer

3: Dim intPress As Integer

4:

5: ' Get the age in a string variable

6: strAge = InputBox("How old are you?", "Age Ask")

7:

8: ' Check for the Cancel command button

9: If (strAge = "") Then

10: End ' Terminate the program

11: End If

12:

13: ' Cancel was not pressed, so convert Age to integer

14: intAge = Val(strAge)

15: ' Loop if the age is not in the correct range

16: Do Until ((intAge >= 10) And (intAge <= 99))

17: ' The user's age is out of range

18: intPress = MsgBox("Your age must be " & _

19: "between 10 and 99", vbExclamation, "Error!")

20: strAge = InputBox("How old are you?", "Age Ask")

21: ' Check for the Cancel command button

22: If (strAge = "") Then

23: End ' Terminate the program

24: End If

25: intAge = Val(strAge)

26: Loop

The 15th line is the only line that marks the difference between Listing 8.1 and Listing 8.2. The age must now fall within the valid range for the loop to terminate.

Top Home