Microsoft Office Tutorials and References
In Depth Information
Controlling Execution
h Do While loops
h Do Until loops
h 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-making capability. The basic
syntax of the If-Then construct is as follows:
If condition Then true_instructions [Else false_instructions]
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 Function 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 (but with a much wider range of dates). 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, the function starts out
by assigning an empty string to GreetMe . The If-Then statement checks the time of day. If the
time is before noon, the Then part of the statement executes, and the function returns Good
Morning .
Function GreetMe()
GreetMe = “”
If Time < 0.5 Then GreetMe= “Good Morning”
End Function
The following function uses two If-Then statements. It displays either Good Morning or
Good Afternoon :
Function GreetMe()
If Time < 0.5 Then GreetMe = “Good Morning”
If Time >= 0.5 Then GreetMe = “Good Afternoon”
End Function
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