Documentation Center

Select-Case Structure

The If-Then-Else statements can as mentioned be nested and make is possible to choose between many different possibilities. They tend to get a bit complicated and the code tends to look messy if you use to many nested If statements. When you need Basic to choose between lots of different options, the Select Case structure is a better solution.

The general form is:

Select Case [Expression]
  Case [Expression]
    [Statements]
  Case [Expression]
    [Statements]
  Case Else
    [Statements]
End Select

In a practical example it could look like this.

Sub Season()
  Dim TodaysMonth As Date
  TodaysMonth = Month(Now)
  
  Select Case TodaysMonth
    Case 1 To 2
      MsgBox "Winter"
    Case 3 To 5
      MsgBox "Spring"
    Case 6 To 8
      MsgBox "Summer"
    Case 9 To 10
      MsgBox "Autum"
    Case Else
      MsgBox "Winter"
  End Select
End Sub

You should use the Select Case structure when making choices based on more than three or four possibilities. It makes the code easier to read, and prevents errors. Select Case structures can also be nested, and you can have If structures nested inside the Select Case structures.