Microsoft Office Tutorials and References
In Depth Information
Controlling Code Execution
Sub Discount1()
Dim Quantity As Variant
Dim Discount As Double
Quantity = InputBox(“Enter Quantity: “)
If Quantity = “” Then Exit Sub
If Quantity >= 0 Then Discount = 0.1
If Quantity >= 25 Then Discount = 0.15
If Quantity >= 50 Then Discount = 0.2
If Quantity >= 75 Then Discount = 0.25
MsgBox “Discount: “ & Discount
End Sub
Notice that each If-Then statement in this procedure is always executed, and the value for
Discount can change. The final value, however, is the desired value.
The following procedure is the previous one rewritten to use the alternate syntax. In this case, the
procedure ends after executing the True instruction block.
Sub Discount2()
Dim Quantity As Variant
Dim Discount As Double
Quantity = InputBox(“Enter Quantity: “)
If Quantity = “” Then Exit Sub
If Quantity >= 0 And Quantity < 25 Then
Discount = 0.1
ElseIf Quantity < 50 Then
Discount = 0.15
ElseIf Quantity < 75 Then
Discount = 0.2
Else
Discount = 0.25
End If
MsgBox “Discount: “ & Discount
End Sub
I find nested If-Then structures rather cumbersome. As a result, I usually use the If-Then
structure only for simple binary decisions. When you need to choose among three or more
alternatives, the Select Case structure (discussed next) is often a better construct to use.
 
Search JabSto ::




Custom Search