HandsOn Using the Select Case Statement

1. Insert a new module and enter the following DisplayDiscount procedure in the Code window.

Sub DisplayDiscount()

Dim unitsSold As Integer Dim myDiscount As Single unitsSold = InputBox("Enter the number of sold units:") myDiscount = GetDiscount(unitsSold) MsgBox myDiscount End Sub

2. In the same module, enter the following GetDiscount function procedure. Function GetDiscount(unitsSold As Integer)

Select Case unitsSold

Case 1 To 200

GetDiscount =



Case 201 To 500

GetDiscount =



Case 501 To 1000

GetDiscount =



Case Is > 1000

GetDiscount =



End Select End Function

End Select End Function

3. Place the insertion point anywhere within the code of the DisplayDiscount procedure and press F5 to run it.

The DisplayDiscount procedure passes the value stored in the variable unitsSold to the GetDiscount function. When Visual Basic encounters the Select Case statement, it checks whether the value of the first Case clause expression matches the value stored in the unitsSold parameter. If there is a match, Visual Basic assigns a 5% discount (0.05) to the function name, and then jumps to the End Select keywords. Because there are no more

Part I

statements to execute inside the function procedure, Visual Basic returns to the calling procedure DisplayDiscount. Here it assigns the function's result to the variable myDiscount. The last statement displays the value of the retrieved discount in a message box.

Specifying Multiple Expressions in a Case Clause

You may specify multiple conditions within a single Case clause by separating each condition with a comma:

Select Case myMonth

Case "January", "February", "March"

Debug.Print myMonth & ": 1st Qtr." Case "April", "May", "June"

Debug.Print myMonth & ": 2nd Qtr." Case "July", "August", "September"

Debug.Print myMonth & ": 3rd Qtr." Case "October", "November", "December" Debug.Print myMonth & ": 4th Qtr." End Select

0 0

Post a comment