Go to: Articles List

Conditionals Part 2 : If and Select Statements, When and Why

     Knowing when to use the if statement versus when to use the select case statement is fairly easy to understand. The if statement should be used when you are testing a specific condition and expecting only a few results. The select case statement should be used when you are testing a specific condition and are expecting more than a few results.

     Here is an example of an if statement that would be better written as a select case statement:

If a = "1" Then
    'do this
ElseIf a = "2" Then
    'do this
ElseIf a = "3" Then
    'do this
ElseIf a = "4" Then
    'do this
End If

     Are all of those "End If" statements really needed? Yes they are. However, you can get rid of all of those "End If" statements by using a select case statement. This is one reason (not the only one) why the case statement is a much better solution. Here is an example of the above set of code rewritten as a select case statement:

Select Case a
    Case "1"
        'do this
    Case "2"
        'do this
    Case "3"
        'do this
    Case "4"
        'do this
End Select

     Using a select case statement the code looks much cleaner and is a lot easier to read. If you find yourself using more than one or two "Else If" statements it is good coding practice to examine whether a select case statement would be a better choice.