Lesson 14 · Select Case

Select Case

Master VB 2026's cleaner alternative to long ElseIf chains — exact value matching, comma-separated value lists, ranges with To, comparisons with Is, string pattern matching, the powerful Select Case True pattern, and when to choose Select Case over If..ElseIf.

Key Takeaway: Use Select Case when you are comparing one expression against many possible values — it is more readable and typically faster than an equivalent ElseIf chain. VB 2026's Select Case supports exact values, comma-separated lists, ranges (To), and comparison operators (Is >=). The Select Case True pattern elegantly handles complex boolean conditions. Always include a Case Else for safety — it catches unexpected values that would otherwise be silently ignored.

14.1 Basic Select Case Syntax

The expression after Select Case is evaluated once. VB 2026 then compares it against each Case clause top-to-bottom and executes the first match. Unlike C#/Java switch, there is no fall-through — once a case matches, the rest are skipped automatically.

BasicSelectCase.vb — Visual Basic 2026
' Syntax
Select Case expression
    Case value1
        ' runs when expression = value1
    Case value2
        ' runs when expression = value2
    Case Else
        ' runs when no Case matched
End Select

' Day of week example
Dim day = DateTime.Now.DayOfWeek

Select Case day
    Case DayOfWeek.Monday
        lblDay.Text = "Start of the work week"
    Case DayOfWeek.Wednesday
        lblDay.Text = "Midweek"
    Case DayOfWeek.Friday
        lblDay.Text = "TGIF!"
    Case DayOfWeek.Saturday, DayOfWeek.Sunday
        lblDay.Text = "Weekend"
    Case Else
        lblDay.Text = "Regular weekday"
End Select

' Menu selection with Integer
Dim choice As Integer
Integer.TryParse(txtChoice.Text, choice)

Select Case choice
    Case 1 : lblAction.Text = "New file"
    Case 2 : lblAction.Text = "Open file"
    Case 3 : lblAction.Text = "Save file"
    Case 4 : lblAction.Text = "Exit"
    Case Else : lblAction.Text = "Invalid option"
End Select
No fall-through in VB

In C# and Java, forgetting a break in a switch causes code to "fall through" to the next case — a common bug. VB 2026's Select Case has no fall-through. Each matched case runs its block and exits automatically. This makes VB's Select Case safer by default.


14.2 Case Matching Patterns

VB 2026's Case clause supports four matching styles that can be used in the same Select Case block.

PatternSyntaxExampleMatches when
Exact valueCase valueCase 5expression = 5
Value listCase v1, v2, v3Case 1, 3, 5expression is any listed value
RangeCase low To highCase 1 To 10low ≤ expression ≤ high
ComparisonCase Is op valueCase Is >= 90expression satisfies the operator
CasePatterns.vb — Visual Basic 2026
Dim score As Integer = 82

' Mix of exact, range, comparison, and list in same block
Select Case score
    Case Is >= 90         ' comparison: Is operator
        lblGrade.Text = "A+"
    Case 80 To 89           ' range: 80 through 89 inclusive
        lblGrade.Text = "A"
    Case 70 To 79
        lblGrade.Text = "B"
    Case 60 To 69
        lblGrade.Text = "C"
    Case 50 To 59
        lblGrade.Text = "D"
    Case Is < 0             ' comparison: below zero is invalid
        lblGrade.Text = "Invalid"
    Case Else               ' anything else (below 50)
        lblGrade.Text = "F"
End Select

' Value list -- month classification
Dim month = DateTime.Now.Month
Select Case month
    Case 3, 4, 5              ' list: March, April, May
        lblSeason.Text = "Spring"
    Case 6, 7, 8
        lblSeason.Text = "Summer"
    Case 9, 10, 11
        lblSeason.Text = "Autumn"
    Case 12, 1, 2
        lblSeason.Text = "Winter"
    Case Else
        lblSeason.Text = "Unknown month"
End Select

' String matching -- case-insensitive in VB by default
Dim command = txtCommand.Text.Trim().ToLower()
Select Case command
    Case "quit", "exit", "bye"
        Application.Exit()
    Case "help", "?"
        ShowHelp()
    Case "new"
        NewDocument()
    Case Else
        lblStatus.Text = $"Unknown command: {command}"
End Select
Try It — Simulation 14.1: Case Pattern Explorer

Enter a score and see which Case clause matches — each clause is highlighted as MATCH or SKIP, showing the exact pattern that fired.

Select Case Pattern Explorer
Score (0–100):

14.3 Select Case vs If..ElseIf

Both structures solve multi-way decisions. Choose the right one based on the problem shape.

If..ElseIf (Lesson 13 style)
If score >= 90 Then
    grade = "A+"
ElseIf score >= 80 Then
    grade = "A"
ElseIf score >= 70 Then
    grade = "B"
ElseIf score >= 60 Then
    grade = "C"
Else
    grade = "F"
End If
Select Case (cleaner)
Select Case score
    Case Is >= 90
        grade = "A+"
    Case 80 To 89
        grade = "A"
    Case 70 To 79
        grade = "B"
    Case 60 To 69
        grade = "C"
    Case Else
        grade = "F"
End Select
Use Select Case when…Use If..ElseIf when…
Comparing one variable against many valuesEach condition tests a different variable
You have 4+ branches on the same expressionYou only have 2–3 branches
Values are discrete (menu items, day numbers, strings)Conditions involve different expressions combined with AndAlso/OrElse
Ranges and value lists are natural fitsYou need short-circuit evaluation (AndAlso)

14.4 Select Case True — The Power Pattern

Select Case True evaluates each Case as a Boolean expression and runs the first one that is True. This combines the readability of Select Case with the flexibility of If..ElseIf for complex conditions.

SelectCaseTrue.vb — Visual Basic 2026
' Select Case True: each Case is a Boolean expression
Dim age As Integer = 25
Dim income As Decimal = 4500

Select Case True
    Case age < 18
        lblCategory.Text = "Minor -- not eligible"
    Case age >= 18 AndAlso income < 2000
        lblCategory.Text = "Young adult, low income"
    Case age >= 18 AndAlso income >= 2000 AndAlso income < 5000
        lblCategory.Text = "Adult, medium income"
    Case age >= 18 AndAlso income >= 5000
        lblCategory.Text = "Adult, high income"
    Case Else
        lblCategory.Text = "Unknown category"
End Select

' BMI classification using Select Case True
Dim bmi = weight / (height ^ 2)

Select Case True
    Case bmi < 18.5
        lblBMI.Text = "Underweight"
        lblBMI.ForeColor = Color.Blue
    Case bmi < 25.0
        lblBMI.Text = "Normal weight"
        lblBMI.ForeColor = Color.Green
    Case bmi < 30.0
        lblBMI.Text = "Overweight"
        lblBMI.ForeColor = Color.Orange
    Case Else
        lblBMI.Text = "Obese"
        lblBMI.ForeColor = Color.Red
End Select
Select Case True vs If..ElseIf

The Select Case True pattern is preferred when you have 4+ branches that each test a different Boolean condition. It reads as a clean list of named outcomes rather than a chain of ElseIfs, making the intent of each branch immediately obvious at a glance.


14.5 Practical Examples

Example 14.1 — Calculator with Operator Select

Calculator.vb — Visual Basic 2026
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    Dim a, b As Double
    If Not Double.TryParse(txtA.Text, a) OrElse Not Double.TryParse(txtB.Text, b) Then
        lblResult.Text = "Enter valid numbers." : Return
    End If

    Dim op = cboOp.Text       ' "+", "-", "*", "/"
    Dim result As Double

    Select Case op
        Case "+" : result = a + b
        Case "-" : result = a - b
        Case "*" : result = a * b
        Case "/"
            If b = 0 Then
                lblResult.Text = "Cannot divide by zero." : Return
            End If
            result = a / b
        Case "^" : result = Math.Pow(a, b)
        Case "Mod" : result = a Mod b
        Case Else
            lblResult.Text = "Select an operator." : Return
    End Select

    lblResult.Text = $"{a} {op} {b} = {result:G}"
End Sub

Example 14.2 — Role-Based Menu System

RoleMenu.vb — Visual Basic 2026
Private Sub SetupMenuForRole(role As String)
    ' First hide everything
    mnuAdmin.Visible  = False
    mnuManager.Visible = False
    mnuReports.Visible = False
    mnuBasic.Visible  = True   ' always visible

    Select Case role.ToLower()
        Case "admin"
            mnuAdmin.Visible   = True
            mnuManager.Visible = True
            mnuReports.Visible = True
            lblRole.Text = "Administrator -- Full Access"
        Case "manager"
            mnuManager.Visible = True
            mnuReports.Visible = True
            lblRole.Text = "Manager -- Standard Access"
        Case "staff", "employee"
            mnuReports.Visible = True
            lblRole.Text = "Staff -- Limited Access"
        Case "guest"
            lblRole.Text = "Guest -- Read-Only"
        Case Else
            lblRole.Text = "Unknown role -- access denied"
            Application.Exit()
    End Select
End Sub
Try It — Simulation 14.2: Operator Calculator

Select Case on a string operator — enter two numbers and pick an operator to see the matching Case branch execute.

Operator Calculator
Number A:
Operator:
Number B:
Try It — Simulation 14.3: Day & Season Classifier

Demonstrates value lists and ranges on integer values — day of week and month classification.

Day & Season Classifier
Day of Week
Day number (0=Sun, 6=Sat):
Month / Season
Month (1–12):

14.6 String Select Case

Select Case works seamlessly with strings. By default VB compares strings case-insensitively when the Option Compare Text module setting is used, or you can .ToLower() the expression for guaranteed case-insensitive matching.

StringSelectCase.vb — Visual Basic 2026
' HTTP status code handler
Dim statusCode As Integer = httpResponse.StatusCode

Select Case statusCode
    Case 200
        lblStatus.Text = "200 OK"           : lblStatus.ForeColor = Color.Green
    Case 201
        lblStatus.Text = "201 Created"      : lblStatus.ForeColor = Color.Green
    Case 301, 302
        lblStatus.Text = "3xx Redirect"     : lblStatus.ForeColor = Color.Orange
    Case 400
        lblStatus.Text = "400 Bad Request"  : lblStatus.ForeColor = Color.Red
    Case 401, 403
        lblStatus.Text = "Auth error"       : lblStatus.ForeColor = Color.Red
    Case 404
        lblStatus.Text = "404 Not Found"    : lblStatus.ForeColor = Color.Red
    Case 500
        lblStatus.Text = "500 Server Error" : lblStatus.ForeColor = Color.DarkRed
    Case Is >= 200, Is <= 299
        lblStatus.Text = "2xx Success"      : lblStatus.ForeColor = Color.Green
    Case Else
        lblStatus.Text = $"Status: {statusCode}"
End Select

' File extension handler using string Select Case
Dim ext = System.IO.Path.GetExtension(fileName).ToLower()
Select Case ext
    Case ".jpg", ".jpeg", ".png", ".gif", ".bmp"
        imgViewer.Load(fileName)
        lblType.Text = "Image file"
    Case ".txt", ".md", ".csv"
        txtEditor.Text = File.ReadAllText(fileName)
        lblType.Text = "Text file"
    Case ".vb", ".cs", ".py", ".js"
        txtEditor.Text = File.ReadAllText(fileName)
        lblType.Text = "Source code"
    Case Else
        lblType.Text = $"Unsupported: {ext}"
End Select
Try It — Simulation 14.4: Select Case True

Demonstrates Select Case True where each Case is a Boolean expression — BMI classifier and income bracket calculator side by side.

Select Case True Demo
BMI Classifier
Weight (kg):
Height (m):
Income Tax Bracket (MY)
Annual Income (RM):
Try It — Simulation 14.5: Role-Based Access Panel

String Select Case driving a role-based access control system — each role unlocks a different set of buttons.

Role-Based Access Control
Select Role:

14.7 GitHub Copilot — Select Case Patterns

GitHub Copilot — HTTP Status Handler
You typed: ' Handle HTTP status codes: group 2xx as success, 3xx as redirect, 4xx as client error, 5xx as server error. Show appropriate message and icon in lblStatus.'
' Handle HTTP status codes: group 2xx as success, 3xx as redirect, 4xx as client error, 5xx as server error.
Dim code As Integer
If Not Integer.TryParse(txtStatusCode.Text, code) Then
    lblStatus.Text = "Invalid status code." : Return
End If

Select Case code
    Case 200 : lblStatus.Text = "OK"
    Case 201 : lblStatus.Text = "Created"
    Case 204 : lblStatus.Text = "No Content"
    Case 200 To 299
        lblStatus.Text = $"Success ({code})"
        picIcon.Image = imgSuccess
    Case 301, 302, 307, 308
        lblStatus.Text = $"Redirect ({code})"
        picIcon.Image = imgRedirect
    Case 400 : lblStatus.Text = "Bad Request"
    Case 401 : lblStatus.Text = "Unauthorized"
    Case 403 : lblStatus.Text = "Forbidden"
    Case 404 : lblStatus.Text = "Not Found"
    Case 400 To 499
        lblStatus.Text = $"Client Error ({code})"
        picIcon.Image = imgError
    Case 500 : lblStatus.Text = "Internal Server Error"
    Case 500 To 599
        lblStatus.Text = $"Server Error ({code})"
        picIcon.Image = imgServerError
    Case Else
        lblStatus.Text = $"Unknown: {code}"
End Select
GitHub Copilot — Currency Converter
You typed: ' Currency converter: Select Case on currency code string. Support MYR, USD, EUR, GBP, JPY, SGD. Base currency is MYR. Show converted amount.'
' Currency converter: Select Case on currency code string. Base currency is MYR.
Dim amount As Decimal
If Not Decimal.TryParse(txtAmount.Text, amount) OrElse amount <= 0 Then
    lblResult.Text = "Enter a positive amount." : Return
End If

Dim currency = cboCurrency.SelectedItem.ToString().ToUpper()
Dim rate As Double
Dim symbol As String

Select Case currency
    Case "MYR" : rate = 1.0     : symbol = "RM"
    Case "USD" : rate = 0.213   : symbol = "$"
    Case "EUR" : rate = 0.197   : symbol = "€"
    Case "GBP" : rate = 0.169   : symbol = "£"
    Case "JPY" : rate = 32.1    : symbol = "¥"
    Case "SGD" : rate = 0.285   : symbol = "S$"
    Case Else
        lblResult.Text = $"Currency '{currency}' not supported."
        Return
End Select

Dim converted = CDbl(amount) * rate
lblResult.Text = $"RM {amount:N2} = {symbol}{converted:N2} ({currency})"
lblRate.Text   = $"Rate: 1 MYR = {rate:G} {currency}"
Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while writing Select Case code:

  • "Convert a grade letter (A+, A, B, C, D, F) back to a numeric GPA value using Select Case on a String"
  • "Build a postcode state lookup: given the first 2 digits, return the Malaysian state name using Select Case with ranges"
  • "Create a simple state machine for a traffic light: Green/Yellow/Red with a timer, use Select Case on the current state"
  • "Use Select Case True to classify a product price into Budget/Mid-range/Premium/Luxury tiers"

Lesson Summary

  • Select Case evaluates an expression once and compares it against each Case clause. The first match executes; there is no fall-through. Always include Case Else to handle unexpected values.
  • Four matching patterns: exact value (Case 5), value list (Case 1, 3, 5), range (Case 1 To 10), comparison (Case Is >= 90). These can be mixed in one block.
  • Select Case is preferred over If..ElseIf when comparing one expression against 4+ values, especially with discrete values, ranges, or lists. Use If..ElseIf when conditions involve different variables combined with AndAlso/OrElse.
  • Select Case True is a powerful pattern where each Case is a Boolean expression — combines the readability of Select Case with the flexibility of If..ElseIf for complex conditions.
  • String Select Case is case-insensitive by default with Option Compare Text. For guaranteed case-insensitive matching, call .ToLower() on the expression before the Select Case.
  • Comma-separated value lists in a single Case (Case "quit", "exit", "bye") are more readable and efficient than multiple separate Cases for the same action.
  • GitHub Copilot generates complete Select Case blocks from a comment describing the values and their actions — ideal for lookup tables, state machines, and role-based access patterns.

Exercises

Exercise 14.1 — Simple Calculator

  • Build a calculator with two TextBoxes (A, B) and a ComboBox for operator (+, -, *, /, ^, Mod)
  • Use Select Case on the operator string to perform the correct calculation
  • Handle division by zero with an If check inside the Case "/" block
  • Display the full expression and result: "12 * 4 = 48"
  • Copilot challenge: Ask Copilot to "add a history ListBox that stores the last 10 calculations"

Exercise 14.2 — Malaysian Postcode State Finder

  • Enter a 5-digit Malaysian postcode in a TextBox
  • Extract the first 2 digits and use Select Case with To ranges to identify the state
  • Ranges: 01–02 Perlis, 05–09 Kedah, 10–14 Penang, 15–18 Kelantan, 20–24 Terengganu, 25–28 Pahang, 30–34 Perak, 35–36 Perak, 40–68 Selangor/KL, 70–73 Negeri Sembilan, 75–77 Malacca, 80–86 Johor
  • Show the state name and a fun fact about the state
  • Copilot challenge: Ask Copilot to "add Sabah/Sarawak postcodes (88xxx-98xxx) with their districts"

Exercise 14.3 — Traffic Light State Machine

  • Create a form with a PictureBox showing Red/Yellow/Green coloured circles
  • Use Select Case on a String state variable ("Red", "Yellow", "Green")
  • A Timer advances the state: Red → Green → Yellow → Red with different durations
  • Show a Label: "STOP", "GO", "SLOW DOWN" matching the current state
  • Copilot challenge: Ask Copilot to "add a pedestrian crossing button that inserts a Walk state after Red"

Next: Lesson 15 — Looping

Learn VB 2026's loop structures — For..Next, For Each..Next, Do While..Loop, Do Until..Loop, and Do..Loop While — with Exit and Continue to control iteration flow.

Continue »

Related Resources


Featured Books

Visual Basic 2022 Made Easy

Visual Basic 2022 Made Easy

by Dr. Liew Voon Kiong

Covers Select Case with practical menu systems, state machines, and multi-condition decision programs.

View on Amazon →
VB Programming With Code Examples

VB Programming With Code Examples

by Dr. Liew Voon Kiong

48 fully-explained VB.NET programs including role-based access, calculators, and lookup-table patterns.

View on Amazon →