Microsoft Office Tutorials and References
In Depth Information
Controlling Code Execution
The basic syntax of the If-Then construct is
If condition Then true_instructions [Else false_instructions]
The If-Then construct is used to execute one or more statements conditionally. The Else
clause is optional. If included, the Else clause lets you execute one or more instructions when
the condition that you’re testing isn’t True .
The following procedure demonstrates an If-Then structure without an Else clause. The
example deals with time, and VBA uses a date-and-time serial number system similar to Excel’s.
The time of day is expressed as a fractional value — for example, noon is represented as .5 . The
VBA Time function returns a value that represents the time of day, as reported by the system
clock. In the following example, a message is displayed if the time is before noon. If the current
system time is greater than or equal to .5 , the procedure ends, and nothing happens.
Sub GreetMe1()
If Time < 0.5 Then MsgBox “Good Morning”
End Sub
Another way to code this routine is to use multiple statements, as follows:
Sub GreetMe1a()
If Time < 0.5 Then
MsgBox “Good Morning”
End If
End Sub
Notice that the If statement has a corresponding End If statement. In this example, only one
statement is executed if the condition is True . You can, however, place any number of
statements between the If and End If statements.
If you want to display a different greeting when the time of day is after noon, add another
If-Then statement, like so:
Sub GreetMe2()
If Time < 0.5 Then MsgBox “Good Morning”
If Time >= 0.5 Then MsgBox “Good Afternoon”
End Sub
Notice that I used >= (greater than or equal to) for the second If-Then statement. This covers
the remote chance that the time is precisely 12:00 noon.
 
Search JabSto ::




Custom Search