Chapter 13. Control Statements

We conclude our discussion of the VBA language with a discussion of the main VBA control statements, which are statements that affect the flow of control (or flow of execution) in a program.

The If...Then Statement

The If...Then statement is used for conditional control. The syntax is:

If Condition Then
   ' statements go here . . .
ElseIf AnotherCondition Then
   ' more statements go here . . .
Else
   ' more statements go here . . .
End If

Note that we may include more than one ElseIf part, and that both the ElseIf part(s) and the Else part are optional. We can also squeeze all parts of this statement onto a single line, which is generally only a good idea when the ElseIf and Else parts are not required.

To illustrate, the following code checks to see if the FirstName field is null. If so, it replaces the Null value with a question mark. If not, it capitalizes the first name.

rs.Edit

If IsNull(rs!FirstName) Then
   rs!FirstName = "?"
Else
   rs!FirstName = UCase(rs!FirstName)
End If

rs.Update

Get Access Database Design and Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.