HandsOn Using Nested IfThen Statements

1. Create a simple form with two text boxes and one command button.

2. Set the properties of the controls you placed on the form as follows:

Control Type

Name Property

Caption Property

Text Box


Text Box


Command Button



Label (in front of txtUser)


Label (in front of txtPwd)


3. Right-click the OK button and choose Build Event from the shortcut menu. In the Choose Builder dialog box, select Code Builder and click OK.

4. Enter the code for the cmdOK_Click event procedure as shown below. Private Sub cmdOK_Click()

Introduction to Access 2003 VBA Programming

If txtPwd = "FOX" Then

MsgBox "You are not authorized to run this report."

Elself txtPwd = "DOG" Then

If txtUser = "John" Then

MsgBox "You are logged on with restricted privileges."

ElseIf txtUser = "Mark" Then

MsgBox "Contact the Admin now."

ElseIf txtUser = "Anne" Then MsgBox "Go home."


MsgBox "Incorrect User name."

End If


MsgBox "Incorrect password or user name"

End If

Me.txtUser.SetFocus End Sub

5. Save your form as frmTestNesting.

To make the cmdOK_Click procedure easier to understand, the conditional statements are shown with different formatting (bold and underlined).

The procedure first checks if the txtPwd text box placed on the form holds the text string "FOX." If this is true, the message is displayed, and Visual Basic skips over the ElseIf and Else clauses until If finds the matching End If (see the bolded conditional statement).

If the text box strPwd holds the string "DOG," then we use a nested If.. .Then.. .Else statement (underlined) to check if the content of the txtUser text box is set to John, Mark, or Anne, and display the appropriate message. If the user name is not one of the specified names, then the condition is false and we jump to the underlined Else to display a message stating that the user entered an incorrect user name.

The first If block (in bold) is called the outer If statement. This outer statement contains one inner If statement (underlined).

0 0

Post a comment