I conclude our discussion of the VBA language with the main VBA control statements, which are statements that affect the flow of control (or flow of execution) in a program.
If...Then statement is used for conditional control. The syntax
ConditionThen ' statements go here . . . ElseIf
AnotherConditionThen ' 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
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
Else parts are not required.
To illustrate, the following code checks to see if the
FirstName field is null. If so, it replaces
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
For...Next statement provides a method for repeatedly looping through a block of code (that is, one or more
lines of code). This loop is naturally referred to as a
For loop. The basic syntax is:
For counter = start To end ' block of code goes here . . . Next counter
The first time that the block of code is executed, the variable
counter (called the loop variable for the
For loop) is given the value
start. Each subsequent time that the block of code is executed, the loop variable ...