Overbasic – Select Case

Table of Contents

SELECT CASE statement is used to select which code block to execute based on an expression result.

Syntax #

Select Case <expression>
Case <value/expression>[, <value/expression>, <value/expression>]
    <code block>
Case <value/expression>[, <value/expression>, <value/expression>]
    <code block>
Case <value/expression>[, <value/expression>, <value/expression>]
    <code block>
[Case Else]
    [<code block>]
EndSelect
  • <expression>: any numeric expression
  • The various <value/expression> in CASEs are expressions or numeric values to be compared with the value of <expression>. Each Case can have several comma-separated <value/expression>.
  • The Case Else block is optional and is executed only if no match is found between the value of <expression> and the various CASEs

How it works:
1) The Select Case expression is evaluated once
2) The value of <expression> is compared with the values of each Case
3) If there is a match, the associated block of code is executed
4) If there is NO match, the code block associated with Case Else is executed (if any).

Examples:

'Getting month name based on month number.
'In this example there is no CASE ELSE.

Dim month As Numeric = 5

Select Case month 
Case 1
    monthName = "January"
Case 2
    monthName = "February"
Case 3
    monthName = "March"
Case 4
    monthName = "April"
Case 5
    monthName = "May"
Case 6
    monthName = "June"
Case 7
    monthName = "July"
Case 8
    monthName = "August"
Case 9
    monthName = "September"
Case 10
    monthName = "October"
Case 11
    monthName = "November"
Case 12
    monthName = "December"
EndSelect

'The result is: May
'Getting the days in a month, based on month number

Dim month As Numeric = 5
Dim daysInMonth As Numeric = 0

Select Case month 
Case 2  
    'check if the year is a leap year
    If (Math.Mod(Year, 400) = 0) Or ((Math.Mod(Year, 4) = 0) And (Math.Mod(Year, 100) <> 0)) Then
        daysInMonth = 29
    Else
        daysInMonth = 28
    EndIf
Case 4, 6, 9, 11
    daysInMonth = 30
Case Else
    daysInMonth = 31
EndSelect

'The result is: 31