|
Select CaseWhy use Select Case?The If...Then...Else...End If structure is fine for making decisions with a few outcomes based on a condition being true or false. When you need to test many conditions and produce a large number of outcomes the If structure is difficult to use effectively. The Select Case structure is designed for this type of problem. You can create as many conditions to test as you need and create an outcome for each condition. Basic Structure of Select CaseSelect Case variablename Case <expression which may match variablename> 'examples of expressions follow: <statement/s> 'statements are executed if the previous expression matches variablename Case <expression which may match variablename> <statement/s> 'statements are executed if the previous expression matches variablename [Case Else 'optional <statement/s>] 'statements are executed if the none of the case expressions match the variablename End Select When the computer encounters the first line of the Select Case, it must have a variable that has had a value assigned to it. This line is followed by as many Case statements as needed to test various comparisons against the variable in the first line. The comparison that is the first to return a true value, is the one whose <statements> are executed. If none of the Case statement's expressions match the variable and there is no Case Else statement, then no action is performed by the Select Case structure. If there is a Case Else statement and no Case statement's expression match, then the statements after the Case Else statement are executed. *Note* the case values can any type of data in proper form, or values stored in variables of the same type as the Case variable. Various Case Expressions
If you want to compare the value stored in the Select Case variable to see if it equals a value, then simply put the value to compare following the Case keyword. For example, to compare the variable value with zero(0), type: Case 0
If you want to use any of the other five conditional operators to compare the variable with a value, then you must follow the Case keyword with the keyword Is which is followed by the conditional operator and then the value. For example, to see if the variable value is less that 23, type: Case Is < 23
If you want to see if the value in the variable is in the range between two values, then you follow the Case keyword with the smallest value of the range followed by the keyword To which is followed by the largest value of the range. For example, to see if the variable value falls in the range 1 to 10, type: Case 1 To 10
You may mix the three types together if need be. For example a valid expression could be: Case 1,6,8 To 12, Is >30 This case is executed it the variable contains a 1,6,8,9,10,11,12 and any value larger than 30 |