Search notes:

VBA statement: select

The select statement allows to abbreviate repeated testing of the same variable with different values using the if x = "foo" … elseif x = "bar" … elseif x = "baz" more elegantly.
The statement roughly mimics the C switch statement.
The optional case else branch is executed if all other tests were false.
option explicit

sub main() ' {

  debug.print(" 1: " & num_to_text( 1))
  debug.print(" 5: " & num_to_text( 5))
  debug.print("42: " & num_to_text(42))

end sub ' }

private function num_to_text(i as long) as string ' {

  select case i
      case 1   : num_to_text = "one"
      case 2   : num_to_text = "two"
      case 3   : num_to_text = "three"
      case 4   : num_to_text = "four"
      case 5   : num_to_text = "five"
      case 6   : num_to_text = "six"
      case 7   : num_to_text = "seven"
      case 8   : num_to_text = "eight"
      case 9   : num_to_text = "nine"
      case else: num_to_text = "Too big!"
  end select

end function ' }
Github repository about-VBA, path: /language/statements/select/basic.bas

Using a range

option explicit

sub main() ' {

  debug.print(gaugeNumber(   42))
  debug.print(gaugeNumber(    7))
  debug.print(gaugeNumber(  800))
  debug.print(gaugeNumber(- 111))

end sub ' }

private function gaugeNumber(i as long) as string ' {

  select case i
      case   1 to   9: gaugeNumber = i & " is a small number"
      case  10 to  99: gaugeNumber = i & " is a medium number"
      case 100 to 999: gaugeNumber = i & " is a large number"
      case else      : gaugeNumber = "I won't say anything about " & i
  end select

end function ' }
Github repository about-VBA, path: /language/statements/select/range.vb

Lists etc.

option explicit

sub main()

    X "Hello world"
    X "FOO"
    X "foo"
    X "alpha"
    X "Beta"
    X "One"
    X "one"

end sub

sub X(val as string)

    dim res as string
    select case val

       case "foo", "bar", "ba"
            res = "metasyntactic variable"

       case "A" to "G", "X" to "Z", lcase(val) = "one"
          '
          ' Note lcase(val) = "one" probably does not what was
          ' intended.
          '
            res = "between A and G, between X and Z or true"

       case else
            res = "> G"

     end select

     debug.print(val & ": " & res)

end sub
'
' Hello world: > G
' FOO: between A and G, between X and Z or case insenstive 'one'
' foo: metasyntactic variable
' alpha: > G
' Beta: between A and G, between X and Z or case insenstive 'one'
' One: > G
' one: > G
Github repository about-VBA, path: /language/statements/select/lists-etc.vb

See also

The choose and switch functions and the if statement.
enums
VBA statements

Index