Visual Basic Select Case

The Visual Basic SELECT CASE statement is a variation of the conditional loop. It compares the same expression to several different values.

An IF-THEN-ELSEIF statement is a more robust conditional loop as it can compare different expressions in each statement. However, the SELECT CASE statement makes your code easier to read.

Visual Basic compares the value of the expression to the values in CASE statements in the order they appear in SELECT CASE block. If it finds a match or a CASE ELSE statement, it executes the corresponding statement block. In any case, it then executes the code following the END SELECT statement. Let's see an example.DIM YourAge as Integer

SELECT CASE Int(YourAge)
  CASE 0 TO 1
    MsgBox "Baby"
  CASE 2 TO 10
    MsgBox "Kid"
  CASE 11 TO 19
    MsgBox "Teenager"
  CASE 20 TO 35
    MsgBox "Young man"
  CASE 36 TO 59
    MsgBox "Middle-aged man"
  CASE 60 TO 99
    MsgBox "Old man"
  CASE IS >= 100
    MsgBox "You are so lucky!"
  CASE Else
    MsgBox "Your age cannot be determined"
END SELECT
The above visual basic SELECT CASE example uses two keywords – ‘TO’ and ‘IS’. The ‘TO’ keyword is used when you want to check the value of an expression between two ranges. The ‘IS’ keyword is used to specify a comparison operator to evaluate the value of the expression.



You can also use multiple expressions in each CASE clause. Example: CASE 20 TO 30, 31 TO 35. Sometimes a CASE statement with multiple clauses can exhibit behavior known as short-circuiting. VB evaluates the clauses from left to right, and as soon as a match is found, the remaining clauses are not evaluated. Short-circuiting can improve performance, but it can also produce unexpected results.

Towards the end of the above example, you will notice the CASE ELSE statement. This is equivalent to the ELSE statement in IF-THEN-ELSE. If all the conditions in the CASE clauses fail, the statements under the CASE ELSE clause are evaluated.

If the code within a CASE or CASE ELSE statement block does not need to run any more of the statements in the block, you can exit the block by using the EXIT SELECT statement. This transfers control immediately to the statement following END SELECT.

Should you use SELECT CASE or IF-THEN-ELSEIF?

Fundamentally, it's a matter of programming style. The bottom line is to get the program to work correctly and efficiently. My preferred programming style is IF-THEN-ELSEIF, though it is easier to read and understand the Visual Basic SELECT CASE structure. My mind is practiced and used to the IF-THEN-ELSE conditional evaluation. It may be SELECT CASE for someone else.

Back to Visual Basic Help