In a lot of situations, a number of comparisons based on the input must be made. The solution requires the if..then..else structure within other if..then..else statemetns. This is called nesting, and can become very complex very quickly. An alternate method using a Case statement can often simplify these situaltions..
Parcel-Post Airfreight charges for parcel delivery based on weight. The following is a table of their charges.
|
Weight |
Price |
| < 2 kg | $3.50 |
| 25kg | $5.50 |
| 5kg | $6.50 |
A program is required that will calculate the cost due when the weight is
entered. It is necessary to check to see which category the weight falls in. If
Weight is not less than 2, it must be checked again to see whether it is less
than 5 or greater then 5. The charge, Charge, is calculated based on final
rate.

This is a good opportunity to use the option buttons. If the button is checked (true), then a value for the rate can be assigned.
Also, nested if statements can be used to allow for the three way (or more) selection process.
If Weight1 Then
Set Post To 3.50
ElseIf Weight3 Then
Set Post To 6.50
Else Set Post To 5.50
End If
Write Post
Code
Private Sub CalculateCmd_Click()
Dim Post As Single
If WeightOpt1.checked = True Then
Post = 3.50
ElseIf WeightOpt3.checked = True Then
Post = 6.50
Else
Post = 5.50
End If
MsgBox "The cost is " & Format(Post, "currency")
End Sub
An alternate solution can be achieved using the CASE statement. The case allows us to compare a given variable against a test value. If the test is true, the program control is passed to the next statement outside the case, otherwise it enacts the associated code. In the case below, there is only a command button procedure that controls the program.
Get Weight
Case Weight
Is < 2
Set Post To 3.50
From 2 To 5
Set Post To 5.50
Is > 5
Set Post To 6.50
EndCase
Write Post
Note in this version we use a Textbox to get the weight and also display the cost.
Private Sub CalculateCmd_Click() Dim weight As Single
Dim post As decimal ' 2 decimal places for currency
Dim strweight As String dim weight as sinlge
strweight = txtWeight.Text
weight = Val(strweight)
Select Case weight
Case Is < 2
post = 3.5
Case 2 To 5
post = 5.5
Case Is > 5
post = 6.5
End Select
txtWeight.Text = "Cost is $" & post End Sub
|
INCOME ($) |
TAX PAYABLE |
| 0 100 | $0 |
| 100500 | $0 + 28c per dollar over $100 |
| 5001000 | $ 112 + 32c per dollar over $500 |
| 10002000 | $196 + 46c per dollar over $1000 |
| >2000 | $656 + 60c per dollar over $2000 |
You have been contracted by the Tax Office to write a program that will accept an income and calculate the amount of tax payable. Use the case statement.
Author Mike Leishman
Updated 28 June 1998
edited FDS 28/3/06