Microsoft Office Tutorials and References
In Depth Information
Controlling Execution
Controlling Execution
Some VBA procedures start at the top and progress line by line to the bottom.
Often, however, you need to control the flow of your routines by skipping over
some statements, executing some statements multiple times, and testing conditions
to determine what the routine does next.
This section discusses several ways of controlling the execution of your VBA
procedures:
If-Then constructs
Select Case constructs
For-Next loops
On Error statements
The If-Then construct
Perhaps the most commonly used instruction grouping in VBA is the If-Then
construct. This instruction is one way to endow your applications with decision-mak-
ing capability. The If-Then construct executes one or more statements
conditionally. The Else clause is optional. If included, it enables you to execute one
or more instructions when the condition that you test is not true.
The following procedure demonstrates an If-Then structure without an Else
clause. The example deals with time. VBA uses the same date-and-time serial
number system as Excel. The time of day is expressed as a fractional value — for
example, noon is represented as .5. VBA’s Time function returns a value that represents
the time of day. The following example uses an If-Then statement to check the
time of day. If the time is before noon, the Then part of the statement executes and
the procedure displays a Good Morning message .
Sub GreetMe()
If Time < 0.5 Then MsgBox “Good Morning”
End Sub
The following procedure uses two If-Then statements. It displays either Good
Morning or Good Afternoon :
Sub GreetMe()
If Time < 0.5 Then MsgBox “Good Morning”
If Time >= 0.5 Then MsgBox “Good Afternoon”
End Sub
Notice that the second If-Then statement uses >= (greater than or equal to). This
covers the extremely remote chance that the time is precisely 12:00 noon when the
function is executed.
Search JabSto ::




Custom Search