JMA201-01
Fundamentals of Application Development

DEPARTMENT SCHEDULE SYLLABUS RESOURCES
Select Case

The select case structure is a specialized form of decision structure. Essentially, it is used when you want to test for multiple possible values of one variable, and do an appropriate action based on each value.

In this example of the case statement, we build a simple fortune teller application. The user will enter a month's name, and we will generate a simple fortune based on that value. In this example, we will look at one variable (holding the user's input) and do one of 13 different things, based on the value entered. Why 13? Well, if the user enters January, February, March, or so on we'll show some text with their fortune; however, if they misspell or in some other way enter a value that isn't a month name, we want a "backup plan" option - like an else in the if statement - to handle this situation.

So, here's my sample form:

My button is called btnRun, the textbox is txtUserInput, and the label for output is called lblOutput.

So, in my code, I look for one of the 13 different values of what the user has typed into the box, and do different things. Here's the code:

So - in this structure we could write the following pseudocode (the keywords are bolded):

  1. Select Case variablename (in this instance, not a variable at all, but the text property of our textbox)
  2. Case firstvalue
  3. Statements to run if the variable matches this value
  4. Case secondvalue
  5. Statements to run if the variable matches this value
  6. Case else
  7. Statements to run if the value being tested didn't match any of the provided cases
  8. End select

Note that we need an end select, but not an end case.

This structure is considered more elegant than multiple if statements. We could have said something like this:

Not efficient!

However, this leads to a lot of nested ifs (easy to miss closing one!) and is inefficient because each expression must be tested - we'd have 12 tests. With the select, only one test needs to be done.