Microsoft Office Tutorials and References
In Depth Information
Controlling Code Execution
Another approach is to use the Else clause of the If-Then construct. For example,
Sub GreetMe3()
If Time < 0.5 Then MsgBox “Good Morning” Else _
MsgBox “Good Afternoon”
End Sub
Notice that I used the line continuation sequence; If-Then-Else is actually a single statement.
If you need to execute multiple statements based on the condition, use this form:
Sub GreetMe3a()
If Time < 0.5 Then
MsgBox “Good Morning”
‘ Other statements go here
MsgBox “Good Afternoon”
‘ Other statements go here
End If
End Sub
If you need to expand a routine to handle three conditions (for example, morning, afternoon, and
evening), you can use either three If-Then statements or a form that uses ElseIf . The first
approach is simpler:
Sub GreetMe4()
If Time < 0.5 Then MsgBox “Good Morning”
If Time >= 0.5 And Time < 0.75 Then MsgBox “Good Afternoon”
If Time >= 0.75 Then MsgBox “Good Evening”
End Sub
The value 0.75 represents 6:00 p.m. — three-quarters of the way through the day and a good
point at which to call it an evening.
In the preceding examples, every instruction in the procedure gets executed, even if the first
condition is satisfied (that is, it’s morning). A more efficient procedure would include a structure that
ends the routine when a condition is found to be True . For example, it might display the Good
Morning message in the morning and then exit without evaluating the other, superfluous
conditions. True, the difference in speed is inconsequential when you design a procedure as small as
this routine. But for more complex applications, you need another syntax:
If condition Then
[ElseIf condition-n Then
Search JabSto ::

Custom Search