VB6 Tutorial 19: Select Case

By | 2018-05-06

This lesson takes you through the Select Case block, a very useful decision-making structure in Visual Basic.

The Select Case block provides an efficient way for decision making which is used to execute one block of statement(s) among a list of statement blocks according to the determined value of an expression. The expression is preceded by the “Select Case” phrase. The choices are made based on the value of this expression.

Syntax

Select Case expression
    Case value0
        statements
    Case value1
        statements
    Case value2
        statements
        ...........
        ...............
    Case else
        statements
End select

Example

Dim num As Integer
num = Val(Text1.Text)
Select Case num
Case 0
    Print "You have entered zero"
Case 1
    Print "You have entered one"
Case 2
    Print "You have entered two"
Case Else
    Print "The number you entered is greater than 2"
End Select

One block of statement(s) will be executed depending upon the value of num. If num=0 then, Case 0 will be evaluated and if num =1 then Case 1 will be evaluated.

See the other forms of Select Case Structure in the following programs.

Example

Dim score As Integer
score = Val(Text1.Text)
Select Case score
Case 900 To 1000
    Print "First position"
Case 800 To 899
    Print "Second position"
Case 700 To 799
    Print "Third position"
Case Else
    Print "No position, try again"
End Select

Example

Dim num As Integer
num = Val(Text1.Text)
Select Case num
Case Is > 0
    Print "Positive number"
Case Is < 0
    Print "Negative number"
Case 0
    Print "Zero"
End Select

Example

Select Case value
    Case 0, 1, 2, 3, 4, 5
        Print "The values are 0,1,2,3,4,5"
    Case Else
        Print "Other values"
End Select

Use the attached sample programs to see basic examples of Select … Case in action.

One of the programs (Numbers) uses a function called Val(). We haven’t learned about that one yet, but it is coming in a future lesson. In a nutshell, it converts the numbers in a string variable to a numeric value.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.