Select Case Statement

To avoid complex nested If statements that are difficult to follow, you can use the Select Case statement instead. The syntax of this statement is as follows:

Select Case testExpression Case expressionList1

statements if expressionList1 matches testExpression Case expressionList2

statements if expressionList2 matches testExpression

Part I

Case expressionListN

statements if expressionListN matches testExpression Case Else statements to be executed if no values match testExpression End Select

You can place any number of cases to test between the keywords Select Case and End Case. The Case Else clause is optional. Use it when you expect that there may be conditional expressions that return False. In the Select Case statement, Visual Basic compares each expressionList with the value of testExpression.

Here's the logic behind the Select Case statement. When Visual Basic encounters the Select Case clause, it makes note of the value of testExpression. Then it proceeds to test the expression following the first Case clause. If the value of this expression (expressionList1) matches the value stored in testExpression, Visual Basic executes the statements until another Case clause is encountered, and then jumps to the End Select statement. If, however, the expression tested in the first Case clause does not match the testExpression, Visual Basic checks the value of each Case clause until it finds a match. If none of the Case clauses contain the expression that matches the value stored in testExpression, Visual Basic jumps to the Case Else clause and executes the statements until it encounters the End Select keywords. Notice that the Case Else clause is optional. If your procedure does not use Case Else, and none of the Case clauses contain a value matching the value of testExpression, Visual Basic jumps to the statements following End Select and continues executing your procedure.

Let's look at the example of a procedure that uses the Select Case statement. As you already know, the MsgBox function allows you to display a message with one or more buttons. The result of the MsgBox function can be assigned to a variable. Using the Select Case statement you can decide which action to take based on the button the user pressed in the message box.

0 0

Post a comment