Select Case Blocks

 
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




Download the following programs to learn about the other forms of Select Case block: 


    See the following links to see the code and explanations of the above programs: 

    To understand the "Numbers" programs, you need to learn about the 'Val( )' function.
    This function returns the numbers contained in a string. In other words, it converts the number contained in a string into value.