Lesson 14: Mastering Select Case in VB2022

Implementing efficient decision-making with multiple conditions in Visual Basic

Key Takeaway

Select Case is a powerful alternative to complex If..ElseIf structures when evaluating a single expression against multiple possible values. It creates cleaner, more readable code and is especially efficient for range-based comparisons.

Welcome to Lesson 14 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to implement efficient decision-making with the Select Case structure. You'll discover how to simplify complex conditional logic, handle multiple scenarios elegantly, and create more maintainable code.

Learning Objectives

  • Understand when to use Select Case vs. If..Then..Else
  • Master the Select Case structure syntax
  • Implement range-based comparisons with Case Is and To
  • Combine multiple conditions in a single Case statement
  • Handle unexpected values with Case Else
  • Create practical applications with Select Case
  • Optimize Select Case performance

14.1 Select Case Fundamentals

Select Case evaluates a single expression and executes code blocks based on matching values. It provides a cleaner alternative to complex If..ElseIf structures.

Select Case Structure Diagram

Select Case Structure

14.1.1 When to Use Select Case vs. If..ElseIf

Select Case is ideal when evaluating a single expression against multiple possible values. If..ElseIf is better for complex conditions with multiple variables.

Criteria Select Case If..ElseIf
Expression Evaluates one expression Can evaluate multiple expressions
Readability More readable for multiple values Better for complex conditions
Range Handling Excellent with "To" keyword Requires logical operators
Performance Slightly faster for many cases Comparable for few conditions

14.1.2 Basic Syntax

The fundamental structure of Select Case in VB2022:

BasicSyntax.vb
Select Case expression
    Case value1
        ' Code to execute when expression = value1
    Case value2
        ' Code to execute when expression = value2
    Case value3
        ' Code to execute when expression = value3
    Case Else
        ' Code to execute when no match
End Select

Best Practice

Always include a Case Else block to handle unexpected values. This ensures your program behaves predictably even with unexpected inputs.

14.2 Case Statement Variations

Select Case provides flexible ways to match values beyond simple equality.

14.2.1 Matching Multiple Values

You can match multiple values in a single Case statement by separating them with commas:

MultipleValues.vb
Dim day As Integer = DateTime.Now.DayOfWeek

Select Case day
    Case DayOfWeek.Saturday, DayOfWeek.Sunday
        lblDayType.Text = "Weekend"
        btnWork.Enabled = False
    Case DayOfWeek.Monday To DayOfWeek.Friday
        lblDayType.Text = "Weekday"
        btnWork.Enabled = True
    Case Else
        lblDayType.Text = "Invalid day"
End Select

14.2.2 Range Matching with To

The To keyword allows you to specify value ranges:

RangeMatching.vb
Dim temperature As Double = Double.Parse(txtTemp.Text)

Select Case temperature
    Case Is < 0
        lblStatus.Text = "Freezing"
        pnlWarning.BackColor = Color.Blue
    Case 0 To 10
        lblStatus.Text = "Cold"
        pnlWarning.BackColor = Color.LightBlue
    Case 11 To 20
        lblStatus.Text = "Cool"
        pnlWarning.BackColor = Color.Green
    Case 21 To 25
        lblStatus.Text = "Room Temperature"
        pnlWarning.BackColor = Color.Yellow
    Case 26 To 30
        lblStatus.Text = "Warm"
        pnlWarning.BackColor = Color.Orange
    Case Is > 30
        lblStatus.Text = "Hot"
        pnlWarning.BackColor = Color.Red
    Case Else
        lblStatus.Text = "Invalid temperature"
End Select

14.2.3 Comparison Matching with Is

The Is keyword allows for comparison-based matching:

ComparisonMatching.vb
Dim score As Integer = CInt(txtScore.Text)
Dim grade As String

Select Case score
    Case Is >= 90
        grade = "A"
    Case Is >= 80
        grade = "B"
    Case Is >= 70
        grade = "C"
    Case Is >= 60
        grade = "D"
    Case Else
        grade = "F"
End Select

lblGrade.Text = $"Grade: {grade}"

14.3 Practical Examples

Let's implement real-world applications using Select Case:

1 Traffic Light Simulator

Determine driver action based on traffic light color:

TrafficLight.vb
Private Sub BtnCheckLight_Click(sender As Object, e As EventArgs) Handles BtnCheckLight.Click
    Dim lightColor As String = txtLightColor.Text.ToLower()
    
    Select Case lightColor
        Case "red"
            lblAction.Text = "Stop"
            lblAction.ForeColor = Color.Red
        Case "yellow"
            lblAction.Text = "Prepare to stop"
            lblAction.ForeColor = Color.Orange
        Case "green"
            lblAction.Text = "Go"
            lblAction.ForeColor = Color.Green
        Case "flashing red"
            lblAction.Text = "Stop and proceed with caution"
            lblAction.ForeColor = Color.DarkRed
        Case Else
            lblAction.Text = "Invalid light color"
            lblAction.ForeColor = Color.Black
    End Select
End Sub

2 Shipping Cost Calculator

Calculate shipping costs based on weight and destination:

ShippingCalculator.vb
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles BtnCalculate.Click
    Dim weight As Double
    Dim zone As String = cboZone.SelectedItem.ToString()
    Dim cost As Decimal = 0
    
    If Double.TryParse(txtWeight.Text, weight) Then
        ' Calculate base cost based on weight
        Select Case weight
            Case 0 To 1
                cost = 5.0
            Case 1.01 To 5
                cost = 8.5
            Case 5.01 To 10
                cost = 12.75
            Case Is > 10
                cost = 12.75 + (weight - 10) * 0.75
            Case Else
                MessageBox.Show("Invalid weight entered")
                Return
        End Select
        
        ' Apply zone multiplier
        Select Case zone
            Case "International"
                cost *= 1.5
            Case "Remote"
                cost *= 1.2
            Case "Local"
                ' No additional charge
            Case Else
                MessageBox.Show("Please select a valid zone")
                Return
        End Select
        
        lblCost.Text = cost.ToString("C")
    Else
        MessageBox.Show("Please enter a valid weight")
    End If
End Sub

3 User Role Permissions

Control UI elements based on user roles:

UserRoles.vb
Private Sub SetUserPermissions(role As String)
    ' Reset all permissions
    btnEdit.Enabled = False
    btnDelete.Enabled = False
    btnAdmin.Visible = False
    
    Select Case role
        Case "Administrator"
            btnEdit.Enabled = True
            btnDelete.Enabled = True
            btnAdmin.Visible = True
            lblWelcome.Text = "Admin Dashboard"
        Case "Editor"
            btnEdit.Enabled = True
            lblWelcome.Text = "Editor Dashboard"
        Case "Viewer"
            lblWelcome.Text = "Viewer Dashboard"
        Case Else
            MessageBox.Show("Invalid user role")
            Application.Exit()
    End Select
End Sub

14.3.1 Day of Week Name

Convert a numeric day to its name using Select Case:

DayOfWeek.vb
Private Sub BtnGetDay_Click(sender As Object, e As EventArgs) Handles BtnGetDay.Click
    Dim dayNumber As Integer
    
    ' Validate input
    If Not Integer.TryParse(txtDayNumber.Text, dayNumber) Or dayNumber < 1 Or dayNumber > 7 Then
        lblResult.Text = "Please enter a number between 1 and 7"
        Return
    End If
    
    ' Convert number to day name
    Dim dayName As String
    
    Select Case dayNumber
        Case 1 : dayName = "Sunday"
        Case 2 : dayName = "Monday"
        Case 3 : dayName = "Tuesday"
        Case 4 : dayName = "Wednesday"
        Case 5 : dayName = "Thursday"
        Case 6 : dayName = "Friday"
        Case 7 : dayName = "Saturday"
    End Select
    
    lblResult.Text = $"Day {dayNumber} is {dayName}"
    lblResult.BackColor = Color.LightBlue
End Sub

Lesson Summary

In this lesson, we've covered essential concepts about the Select Case structure in VB2022:

Structure

Select Case expression, Case values, Case Else, End Select

Matching Techniques

Exact values, value lists, ranges (To), comparisons (Is)

Best Practices

Always include Case Else, order cases logically, keep it readable

Use Cases

Menu systems, role-based permissions, grading systems, state machines

Performance

More efficient than If..ElseIf for multiple comparisons of the same expression

These skills will help you create more efficient and readable decision-making logic. In the next lesson, we'll explore looping structures to handle repetitive tasks.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Simple Calculator

Create a calculator that:

  1. Takes two numbers and an operator (+, -, *, /)
  2. Uses Select Case to determine which operation to perform
  3. Handles division by zero with an error message
  4. Displays the result formatted to two decimal places

Exercise 2: Temperature Range Classifier

Build an application that:

  1. Accepts a temperature in Celsius or Fahrenheit
  2. Classifies the temperature into categories (Freezing, Cold, Cool, etc.)
  3. Uses Select Case with range matching
  4. Converts between temperature scales if needed

Exercise 3: Zodiac Sign Finder

Implement a solution that:

  1. Takes a birth month and day as input
  2. Uses Select Case to determine the zodiac sign
  3. Displays the sign's characteristics
  4. Handles invalid dates appropriately

Next Lesson

Ready to learn about repetitive tasks? Continue to Lesson 15: Looping in VB2022.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More