Lesson 8 : Select Case Control Structure

<Previous Lesson> <<Home>> < Next Lesson>

In the previous lesson, we have learned how to control the program flow using If...Then...ElseIf control structure. In this lesson, you shall examine another way to control the program flow, that is, the Select Case control structure. The Select Case control structure is slightly different from the If....ElseIf control structure .The difference is that the Select Case control structure can handle conditions with multiple outcomes in an easier manner than the If...Then...ElseIf control structure. The syntax of the Select Case control structure is shown below:

Select Case expression
    Case value1
	Block of one or  more VB statements
	
	Case value2
	Block of one or more VB Statements

    Case Else
	Block of one or more VB Statements
End Select

Example 8.1

Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
Case "B"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
End Sub


Example 8.2

Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
End Sub

Example 8.3

Example 8.2 can be rewritten  as follows:

Dim mark As Single

Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case 0 to 49
comment.Caption ="Need to work harder"
Case 50 to 59
comment.Caption = "Average"
Case 60 to 69
comment.Caption = "Above Average"
Case 70 to 84
comment.Caption = "Good"
Case Else
comment.Caption ="Excellence"

End Select
End Sub
	

Example 8.4 Guess a Number

In this example, we use the Select Case statement to guess a number generated randomly. The syntax 1 + Int(6 * Rnd) generates a random number from 1 to 6 inclusive

The Code

Dim Secret_Number As Integer


Private Sub Command1_Click()

Dim Your_Number As Integer
Your_Number = InputBox("Enter a number between 1 and 6 includisve")
Select Case Your_Number
Case Is < Secret_Number
MsgBox ("Your number is smaller than the secret number, try again!")
Case Is > Secret_Number
MsgBox ("Your number is greater than the secret number, try again!")

Case Else
Beep
MsgBox ("Your number is correct, congratulation!")
End Select

End Sub

Private Sub Form_Load()
Secret_Number = 1 + Int(6 * Rnd)

End Sub

  Bookmark and Share


<Previous Lesson> <<Home>> < Next Lesson>

Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved |Contact

[Privacy Policy]