Loop termination

As long as the comparison test is true, the block of code in the body of the loop continues executing. When the test becomes false, the loop terminates and VBA begins program execution at the statement following the Loop statement which signals the end of the loop. As soon as the Do While's comparison test becomes false, the loop terminates and doesn't execute even one more time. The test appears at the top of the loop, so if it is false the first time the loop begins, the body of the loop will never execute.

Listing 7.6 contains the same program as in Listing 7. 5 using a Do While ... Loop to asks the user for an age. If the user enters an age less than 25 or more than 65, the program returns an error message as before. It continues looping, asking for the age, as long as the user enters an age that's out of range.

Listing 7.6 Using Do While loop to control a loop

Dim strAge As String Dim intAge As Integer

Dim intPress As Integer 'Get the age in a string variable strAge = InputBox("How old are you?", "Age Ask") ' Check for the Cancel command button If (strAge = "") Then

End 'Terminates the application

End If

'Cancel was not pressed, so convert age to integer using Val() intAge = Val(strAge)

'Loop if the age is not in the correct range Do While ((intAge < 25 ) Or (intAge > 65)) 'The user's age is out of range intPress = MsgBox("Your age must be between " & _

"10 and 65", vbExclamation, "Error!") strAge = InputBox("How old are you?", "Age Ask")

'Check for the Cancel command button If (strAge = "") Then

End 'Terminate the program

End If intAge = Val(strAge) Loop

0 0

Post a comment