Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. The result of the expression is then compared with the values for each Case in the structure. If there is a match, the block of statements associated with that Case is executed, as in the following example.

Select Case Document.Form1.CardType.Options(SelectedIndex).Text
   Case "MasterCard"
      DisplayMCLogo
      ValidateMCAccount
   Case "Visa"
      DisplayVisaLogo
      ValidateVisaAccount
   Case "American Express"
      DisplayAMEXCOLogo
      ValidateAMEXCOAccount
   Case Else
      DisplayUnknownImage
      PromptAgain
End Select

Notice that the Select Case structure evaluates an expression once at the top of the structure. In contrast, the If...Then...ElseIf structure can evaluate a different expression for each ElseIf statement. You can replace an If...Then...ElseIf structure with a Select Case structure only if each ElseIf statement evaluates the same expression.

No comments: