Microsoft Office Tutorials and References
In Depth Information
Controlling Execution
Another approach is to use the Else clause of the If-Then construct:
Function GreetMe()
If Time < 0.5 Then GreetMe = “Good Morning” Else _
GreetMe = “Good Afternoon”
End Function
Notice that the preceding example uses the line continuation sequence (a space followed by an
underscore); If-Then-Else is actually a single statement.
The following is another example that uses the If-Then construct. This Function procedure
calculates a discount based on a quantity (assumed to be an integer value). It accepts one
argument (quantity) and returns the appropriate discount based on that value.
Function Discount(quantity)
If quantity <= 5 Then Discount = 0
If quantity >= 6 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
End Function
Notice that each If-Then statement in this procedure is always executed, and the value for
Discount can change as the function executes. The final value, however, is the desired value.
The preceding examples all used a single statement for the Then clause of the If-Then
construct. However, you often need to execute multiple statements if a condition is TRUE. You can
still use the If-Then construct, but you need to use an End If statement to signal the end of
the statements that make up the Then clause. Here’s an example that executes two statements if
the If clause is TRUE:
If x > 0 Then
y = 2
z = 3
End If
You can also use multiple statements for an If-Then-Else construct. Here’s an example that
executes two statements if the If clause is TRUE, and two other statements if the If clause is not TRUE:
If x > 0 Then
y = 2
z = 3
Else
y = –2
z = –3
End If
 
Search JabSto ::




Custom Search