Select…Case - VBScript


Select…Case

Overview

The Select...Case command allows conditional branching of code flow based on the value of a specified expression. It compares the expression against multiple possible values or ranges of values, and executes the code associated with the matching value.

Syntax

Select Case expression
    Case value1
        [code_to_execute]
    Case value2
        [code_to_execute]
    ...
    Case Else
        [code_to_execute_if_no_match]
End Select

Parameters

  • expression: The expression to evaluate and compare against the case values.
  • value1, value2, …: One or more constant values or ranges of values to compare against the expression.
  • code_to_execute: The code to execute when the expression matches the specified value or range.
  • Case Else: Optional. The code to execute if no other case matches the expression.

Options/Flags

None.

Examples

Simple Example:

Dim myNumber = 5

Select Case myNumber
    Case 1
        MsgBox("Number is 1")
    Case 2
        MsgBox("Number is 2")
    Case 3
        MsgBox("Number is 3")
    Case Else
        MsgBox("Number is not 1, 2, or 3")
End Select

Range Example:

Dim myScore = 85

Select Case myScore
    Case To 60, 69
        MsgBox("Failing: Score is between 60 and 69")
    Case 70, 79
        MsgBox("Passing: Score is between 70 and 79")
    Case 80, 89
        MsgBox("Good: Score is between 80 and 89")
    Case 90 To 100
        MsgBox("Excellent: Score is 90 or above")
    Case Else
        MsgBox("Invalid score")
End Select

Common Issues

  • Incorrect Value Type: Ensure that the expression and case values are of the same data type. Mixing different types (e.g., strings and numbers) may lead to unexpected results.
  • Missing Else Case: If no Case Else is provided, the script may crash if the expression does not match any of the specified values.
  • Overlapping Ranges: Avoid overlapping ranges to ensure that there is only one matching case for each expression value.

Integration

The Select...Case command can be integrated with other VB Script commands to create more complex control flow:

  • With Conditional Statements: Use If...Else statements to filter the expression before entering the Select...Case block, reducing the number of cases to evaluate.
  • Looping: Use For...Next or Do...While loops to iterate through a range of possible values and evaluate them using Select...Case.
  • If…Then…Else: Alternative conditional branching statement.
  • Case: Used to specify a case within a Select...Case block.