HandsOn Using the DoWhile Loop

This chapter's hands-on exercises are provided in the Acc2003_Chap06.mdb file included in the book's downloadable files.

1. Open Acc2003_Chap06.mdb from the downloadable files or, if you'd like to start from scratch, create a new Microsoft Office Access 2003 database.

2. In the Database window, choose Tools | Macro | Visual Basic Editor or press Alt+F11 to switch to the Visual Basic Editor window.

3. Choose Insert | Module to add a new module.

4. In the Code window, enter the AskForPassword procedure shown below.

Sub AskForPassword() Dim pWord As String pWord = ""

Do While pWord <> "DADA"

pWord = InputBox("What is the Report password?")

Loop

MsgBox "You entered the correct Report password."

End Sub

In the above procedure, the statement inside the Do.. .While loop will be executed as long as the variable pWord is not equal to the string DADA. If the user enters the correct password (DADA), Visual Basic leaves the loop and executes the MsgBox statement after the Loop keyword.

To allow the user to exit the procedure gracefully and cancel out the input box if he does not know the correct password, you should add the following statement on an empty line before the Loop keyword:

The Exit Do statement is discussed toward the end of this chapter. This statement tells Visual Basic to exit the Do Loop if the variable pWord does not hold any value. Therefore, when the input box appears, the user can leave the text field empty and click OK or Cancel to stop the procedure. Without the above statement, the procedure will keep on asking the user to enter the password until the correct value is supplied.

To forgo displaying the informational message when the user has not provided the correct password, you may want to use the conditional statement If.. .Then that you learned in the previous chapter. Below is the revised AskForPassword procedure.

Sub AskForPassword2() Dim pWord As String pWord = ""

Do While pWord <> "DADA"

pWord = InputBox("What is the Report password?") If pWord = "" Then Exit Do

Loop

Introduction to Access 2003 VBA Programming

MsgBox "You entered correct password."

End If End Sub

0 0

Responses

  • Heidi
    How to use do while and loop access 2003?
    7 years ago

Post a comment