O'Reilly logo

Beginning Access™ 2007 VBA by Denise Gosnell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.5. Controlling Program Flow

So far, you have learned how to create one or more modules to contain your code as well as how to create procedures within those modules. Now you will see how to write commands within procedures that control the flow of the program. The flow of a program can be controlled through decision-making, loops, and in other ways. We'll start by looking at writing decision-making code.

2.5.1. Decision Making

VBA has various statements you can use to make decisions in your code and then take an appropriate action depending on the result. The following gives you several decision-making examples to illustrate this concept.

2.5.1.1. If ...Then

If...Then statements can be used to make decisions and perform certain actions depending on whether the conditions are met.

The syntax for an If...Then statement is:

If CONDITION Then
'code if the condition is met
End If

The syntax for an If...Then...Else statement is:

If CONDITION Then
'code if the condition is met
Else
'code if the condition is not met
End If

The syntax for an If...Then...ElseIf statement is:

If CONDITION Then
'code if the condition is met
ElseIf CONDITION Then
'code if the ElseIf condition is met
End If

ElseIf and Else can be used together as part of the same If...Then statement, or they can be used separately, as illustrated in the previous example. If...Then statements can also be nested within each other, as shown in the following example:

If intCounter < 0 Then 'reset intCounter to 0 intCounter ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required