Microsoft Office Tutorials and References
In Depth Information
Controlling Code Execution
[Else
[default_instructions]]
End If
Here’s how you can use this syntax to rewrite the GreetMe procedure:
Sub GreetMe5()
If Time < 0.5 Then
MsgBox “Good Morning”
ElseIf Time >= 0.5 And Time < 0.75 Then
MsgBox “Good Afternoon”
Else
MsgBox “Good Evening”
End If
End Sub
With this syntax, when a condition is True , the conditional statements are executed, and the
If-Then construct ends. In other words, the extraneous conditions aren’t evaluated. Although
this syntax makes for greater efficiency, some find the code to be more difficult to understand.
The following procedure demonstrates yet another way to code this example. It uses nested
If-Then-Else constructs (without using ElseIf ). This procedure is efficient and also easy to
understand. Note that each If statement has a corresponding End If statement.
Sub GreetMe6()
If Time < 0.5 Then
MsgBox “Good Morning”
Else
If Time >= 0.5 And Time < 0.75 Then
MsgBox “Good Afternoon”
Else
If Time >= 0.75 Then
MsgBox “Good Evening”
End If
End If
End If
End Sub
The following is another example that uses the simple form of the If-Then construct. This
procedure prompts the user for a value for Quantity and then displays the appropriate discount
based on that value. Note that Quantity is declared as a Variant data type. This is because
Quantity contains an empty string (not a numeric value) if the InputBox is cancelled. To keep
it simple, this procedure doesn’t perform any other error checking. For example, it doesn’t ensure
that the quantity entered is a non-negative numeric value.
 
Search JabSto ::




Custom Search