Select Case

Another way to implement decision making in your VBA code is to use a Select...Case statement. Select...Case statements can be used to easily evaluate the same variable multiple times and then take a particular action depending on the evaluation.

The syntax for a Select...Case statement is:

Select Case VARIABLE Case VALUE1

'code to run if VARIABLE equals Value1 Case VALUE2

'code to run if VARIABLE equals Value2 Case Else

'code to run for remaining cases End Select

Try It Out Create the TestCaseStatement Procedure

Let's create a new procedure that makes use of a Select...Case statement to illustrate this in further detail.

1. Add the following TestCaseStatement procedure to the modBusinessLogic standard module.

Sub TestCaseStatement(strCountry As String)

'evaluate the value of strCountry and display applicable result in debug window Select Case strCountry Case "Italy"

Debug.Print "The buildings dating back to 400 BC are incredible." Case "China"

Debug.Print Case "Russia"

Debug.Print Case "Germany"

Debug.Print Case Else

Debug.Print End Select

Great bargains for shoppers."

A beautiful country with a growing democracy." Fantastic food - you will not starve there." You should travel more when you have the chance."

End Sub

2. Run the TestCaseStatement procedure from the Immediate Window and specify "Italy" as the parameter, as shown in Figure 2.28. Click Enter to run the procedure. The resulting value is then displayed in the Immediate Window.

0 0

Post a comment