|
The Select Case statement is very useful when there is the need to do different things according with an expression value which can have multiple options. Alternatively it is possible to use many If statements, but when the values to test are many, the use of Select Case will assure a more practical and efficient operation.
Let's see how it is the command syntax:
Select Case (Main Expression) Case(Expression1) "Block of instructions"
Case(Expression2) "Block of Instructions"
Case(Expression3) "Block of Instructions" ... other Case ...
Case Else "Block of Instructions"
EndSelect
First of all the command interpreter will get the value of the "Main Expression" Then it will start from the first Case to the last to check the expression of each Case and compare it with the value of the Main Expression. The first time to condition is met, the corresponding Instructions Block will be executed, and all the other parts of the statement will be ignored. If no condition will be satisfied and a Case Else statement exists (being optional) then will be executed the Instructions Block after Case Else, or otherwise nothing will happen.
Let's see an example which will help to understand the flow.
... ... ... MyValue = 10 Select Case MyValue Case 1 S = "2"
Case 10 For a = 1 To 10 S= S & "A" Next a Case 20 S = S & "M" Case Else S = "" EndSelect ... ... ...
"MyValue" is a variable. Before entering the Select Case statement, the variable has been set to 10 (this for simplicity, but it could well have been the result of an expression).
The command interpreter will compare the value of "MyValue" (which is 10) with the expression on the first Case. In this case, the expression to compare evaluates as 1, therefore not equal to 10, which is the value of "MyValue". The second Case is tested. In this case the value of the expression (10) is exactly equal to the value of MyValue (10). Therefore are executed the instructions contained in the second Case statement. When the execution of this set of instruction has been executed, the control will exit from the Select Case, continuing with the following instructions.
So all the other instructions for different cases have not been executed.
NB In case the value of MyValue would have been 100, the command interpreter would not have found any matching expression so the block of code immediately following the Case Else will have been executed instead. If this last condition was missing the no other code will be executed and the control of the program will continue with the subsequent lines.
|