Visual Basic 2005 Guide
The Select Case Statement

The Select .. Case statement works in a very similar way to the If statement but is more useful when you have a lot of conditions to examine. The following code will message box the month which corresponds to a number input by the user. The code assumes a text box called txtMonth and should be run when a button is clicked.

   Dim intMonth As Integer
   intMonth = txtMonth.Text
   Select Case intMonth
      Case 1
         MsgBox "January"
      Case 2
         MsgBox "February"
      Case 3
         MsgBox "March"
      { This carries on up to 12 as you would expect }
      Case Else
         Msgbox "Enter a number from 1 -12 "
   End Select

Finish the code and create a working program.

The Case part of this structure works in a similar way to the If statement. It can be written differently though for different situations. Look at the examples below.

Case 0 To 15Tests whether the value is from 0 to 15
Case Is <40Tests whether the value is less than 40
Case 1, 3, 5Tests whether the value is 1, 3 or 5

Programming Tasks

1. Write a program which allows the user to input the number of a month (from 1 to 12). Your program should tell them how many days are in that month.

2. Write a program that tells a tired old teacher what grade to give a student's work. The teacher should input a number from 0 to 100. Marks below 40 are graded fail, marks from 40 to 59 are graded pass. 60 or more marks will earn a merit and 80 or more scores a distinction.