Como: Testar vários valores de uma expressão (Visual Basic)

When you are comparing the same expression to several different values, you can use the Declaração Select...Case (Visual Basic) construction as an alternative to the Declaração If...Then... (Visual Basic) construction. Whereas the If and ElseIf statements can evaluate a different expression in each statement, the Select statement evaluates a single expression only once and uses it for every comparison.

To evaluate an expression once and test several values

  • Use the Select...Case construction to specify the expression and the values to test. Each Case statement can contain one or more values, a range of values, or a combination of values and comparison operators. You can use a Case Else statement to handle all values not tested by the previous Case statements. The following example illustrates these possibilities.

    Function bonus(ByVal performance As Integer, 
                   ByVal salary As Decimal) As Decimal
        Select performance
            Case 1
                Return salary * 0.1
            Case 2, 3
                Return salary * 0.09
            Case 5 To 7
                Return salary * 0.07
            Case 4, 8 To 10
                Return salary * 0.05
            Case Is < 15
                Return 100
            Case Else
                Return 0
       End Select
    End Function
    

    Visual Basic compares the value of the expression to the values in the Case statements in the order they appear in the Select...Case construction. If it finds a match or a Case Else statement, it runs the corresponding statement block. In any case, it then branches to the statement following the End Select statement.

    You can have any number of Case statements, and you can include or omit one Case Else statement regardless of whether you have any Case statements.

A code example for the Select...Case construction is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic Language. For more information, see Como: Inserir trechos de código de IntelliSense.

Consulte também

Tarefas

Como: Transferir controle para fora de uma estrutura de controle (Visual Basic)

Como: executar instruções dependendo de uma ou mais condições (Visual Basic)

Como: Manter controle quando ocorre um erro (Visual Basic)

Conceitos

Estruturas de decisão (Visual Basic)

Estruturas de loop (Visual Basic)

Outras estruturas de controle (Visual Basic)

Estruturas de controle aninhado (Visual Basic)

Outros recursos

Fluxo de controle no Visual Basic