The Do Until LoopWhereas 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
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.
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. |
|
![]() |
![]() |
|||