Excel VBA Switch Case
Switch Case ou Select Case é uma instrução disponível no VBA para conduzir testes lógicos onde funciona como uma alternativa à instrução IF-THEN no VBA. Usando um caso de switch, podemos conduzir vários testes lógicos e chegar a resultados com base em vários resultados.
Abaixo está a sintaxe da instrução Switch Case / Select Case.
Código:
Selecione o valor do caso 1 se o teste do caso 1 for VERDADEIRO Valor do caso 2 se o teste do caso 2 for VERDADEIRO.
: Qual é o teste lógico? Precisamos entrar no teste aqui.
Caso 1, Caso 2: em cada caso, precisamos testar vários testes lógicos no Excel.
Como usar a declaração de caso do switch VBA?
Exemplo 1
Na célula A1, inseri o valor de 550.
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_2.png.webp)
Testaremos esse número usando declarações switch case e chegaremos ao status “Mais de 500” se o valor for maior que 500 ou então chegaremos ao status “Menos de 500”.
Abra o procedimento Sub do VBA primeiro.
Código:
Sub Switch_Case () End Sub
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_3.png.webp)
Abra Select Case Statement em VBA e forneça o intervalo de teste lógico (“A2”).
Código:
Sub Switch_Case () Selecione Case Range ("A2"). Value End Sub
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_4.png.webp)
Agora insira o primeiro caso, pois o caso é> 500.
Código:
Sub Switch_Case () Selecione Case Range ("A2"). Value Case Is> 500 End Sub
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_5.png.webp)
Se este caso for VERDADEIRO, então qual é o resultado que precisamos na célula B, 2, ou seja, “Mais de 500”.
Código:
Sub Switch_Case () Selecione Case Range ("A2"). Value Case Is> 500 Range ("B2"). Value = "More than 500" End Sub
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_6.png.webp)
Agora ficamos com apenas um resultado, ou seja, a instrução Case Else. Se o primeiro Caso for FALSO, então precisamos do resultado como “Menos de 500”.
Código:
Sub Switch_Case () Selecione Case Range ("A2"). Value Case Is> 500 Range ("B2"). Value = "More than 500" Case Else Range ("B2"). Value = "Less than 500" End Sub
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_7.png.webp)
Agora feche a instrução usando a instrução “End Select”.
Código:
Sub Switch_Case () Selecione Case Range ("A2"). Value Case Is> 500 Range ("B2"). Value = "More than 500" Case Else Range ("B2"). Value = "Less than 500" End Select End Sub
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_8.png.webp)
Execute o código e obteremos o valor na célula B2.
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement.gif)
Como o valor na célula A2 é maior que 500, obtivemos o resultado como “Mais de 500”.
Exemplo # 2
Agora veremos usando mais exemplos de casos. Abaixo está a pontuação do aluno no exame.
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_9.png.webp)
Com essa pontuação, precisamos chegar ao Grau, para isso abaixo estão os critérios.
- Pontuação> = 85, nota = “Dist”
- Pontuação> = 60, nota = “primeiro”
- Pontuação> = 50, nota = “segundo”
- Pontuação> = 35, nota = “aprovado”
- Se qualquer outra coisa, Grau = “Reprovado”.
Código:
Sub Switch_Case1 ()
Dim Score As Integer Score = 65 Selecionar Case Score Case Is> = 85 MsgBox "Dist" Case Is> = 60 MsgBox "First" Case Is> = 50 MsgBox "Second" Case Is> = 35 MsgBox "Pass" Case Else MsgBox " Falha "End Select End Sub
Execute este código. Obteremos a nota na caixa de mensagem.
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_2.gif)
Since the score is more than 60 but less than 85 grade is “First.”
Example #3
We have seen how to find a grade for one student, what about finding a grade for more than one student. Below are the scores of students.
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_10.png.webp)
Since more than one student is involved, we need to enclose FOR NEXT loop in VBA. Below is the VBA code.
Code:
Sub Switch_Case2() Dim k As Integer For k = 2 To 7 Select Case Cells(k, 2).Value Case Is>= 85 Cells(k, 3).Value = "Dist" Case Is>= 60 Cells(k, 3).Value = "First" Case Is>= 50 Cells(k, 3).Value = "Second" Case Is>= 35 Cells(k, 3).Value = "Pass" Case Else Cells(k, 3).Value = "Fail" End Select Next k End Sub
Run this code. We will get grades.
![](https://cdn.know-base.net/9301396/vba_switch_case_examples_to_use_excel_vba_switch_statement_3.gif)
Things to Remember
- Switch Case is often referred to as “Select Case.”
- The switch is a function, not a statement.
- Se nenhum teste lógico for TRUE, você pode simplesmente passar o resultado alternativo na instrução CASE ELSE e sempre fechar a instrução com a palavra “END SELECT”.