Vba excel switch case

Оператор Select Case, выполняющий одну или более групп операторов VBA Excel в зависимости от значения управляющего выражения. Синтаксис, компоненты, примеры.

Оператор Select Case используется в VBA Excel для управления отдельными блоками операторов в зависимости от значения управляющего выражения (переменной) и сравнительных условий, задаваемых ключевым словом Case.

Синтаксис оператора Select Case

Select Case выражение

    Case условие 1

        [операторы 1]

    Case условие 2

        [операторы 2]

    Case условие n

        [операторы n]

    Case Else

        [операторы]

End Select

Компоненты оператора Select Case

  • выражение – любое числовое или строковое выражение, переменная;
  • условие – диапазон значений или выражение с операторами сравнения и ключевым словом Is*;
  • операторы – блок операторов VBA Excel, который выполняется при вхождении значения управляющего выражения в диапазон, заданный в условии, или при возврате выражением с операторами сравнения значения True;
  • блок операторов после ключевой фразы Case Else** выполняется в том случае, если в предыдущих условиях Case не будет найдено совпадений со значением управляющего выражения (переменной).

* Редактор VBA Excel автоматически добавляет ключевое слово Is в условия с операторами сравнения.
** Компонент Case Else с соответствующим блоком операторов необязательны, но рекомендуется их использовать для обработки непредвиденных значений управляющего выражения (переменной).

Примеры использования в VBA Excel

Пример 1

Пример использования оператора Select Case с операторами сравнения в условиях:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Sub primer1()

Dim a As Integer, b As String

a = InputBox(«Введите число от 1 до 5», «Пример 1», 1)

    Select Case a

        Case Is = 1

            b = «один»

        Case Is = 2

            b = «два»

        Case Is = 3

            b = «три»

        Case Is = 4

            b = «четыре»

        Case Is = 5

            b = «пять»

        Case Else

            b = «Число не входит в диапазон от 1 до 5»

    End Select

MsgBox b

End Sub

Этот пример аналогичен первому примеру из статьи VBA Excel. Функция Choose, с помощью которой и следует решать подобные задачи в VBA Excel.

Пример 2

Пример использования оператора Select Case с заданным диапазоном в условиях:

Sub primer2()

Dim a As Integer, b As String

a = InputBox(«Введите число от 1 до 30», «Пример 2», 1)

    Select Case a

        Case 1 To 10

            b = «Число « & a & » входит в первую десятку»

        Case 11 To 20

            b = «Число « & a & » входит во вторую десятку»

        Case 21 To 30

            b = «Число « & a & » входит в третью десятку»

        Case Else

            b = «число « & a & » не входит в первые три десятки»

    End Select

MsgBox b

End Sub

Для решения подобной задачи в VBA Excel можно использовать многострочную конструкцию оператора If…Then…Else, но решение с Select Case выглядит изящней.

VBA Switch Case

Excel VBA Switch Case

In VBA Switch Case, when we need to logically check or analyze a condition and execute the different lines of codes based on the same, we use IF-Else conditional statement. Similarly, there is one more statement Switch Case which is more widely known as Select Case statement which can check or analyze the multiple logical conditions and execute the code lines based on those. When you have three or more logical conditions to check, it is recommended that you use Select Case or Switch Case instead of a conventional IF-Else statement. Because it makes the VBA Code faster and more understandable instead of nested IF-Else statements in such cases.

Switch Case / Select Case

Switch Case or Select Case in VBA works on similar lines as of IF-Else statements. It checks the multiple logical/conditional expressions against different values (cases). As soon as any of the case is matching the condition (becomes true for the given condition), the system executes that case and rest other cases are ignored to execute. In case, there are two cases that are true for the given condition, only the first one will be executed with the law of precedence.

Syntax for Switch Case/Select Case is as below:

Select Case <Expression to check>
Case value_1
Code to Execute when Expression = value_1
Case value_2
Code to Execute when Expression = value_2
Case value_3
Code to Execute when Expression = value_3
.
.
.
Case value_n
Code to Execute when Expression = value_n
Case Else
Code to Execute when no case value meets the expression/logical test.
End Select

Where,

Expression: This is an expression for which we wanted to check or analyze using different case values.

value_1, value_2, value_3, … are the logical conditions that are needed to be checked for the given expression.

How to Use the Switch Case Statement in Excel VBA?

We will learn how to use the Switch Case statement in Excel by using the VBA Code.

You can download this VBA Switch Case Excel Template here – VBA Switch Case Excel Template

VBA Switch Case – Example #1

We will check whether the given number is less than 100 or more than 100. For this, follow the steps below:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Define a new subprocedure within the inserted module that can hold your macro.

Code:

Sub switch_case_example1()

End Sub

VBA Switch Case Example 1-1

Step 3: Define a new variable named usrInpt which can hold the user value. Make use of the VBA InputBox function to create an input box that takes user values through variable usrInpt.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")

End Sub

VBA InputBox function Example 1-2

Step 4: Use the Select Case statement and supply the value provided by the user through variable usrInpt. This is the expression we need to check with logical conditions.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")
Select Case usrInpt

End Sub

Use Select Case statement

Step 5: Enter the first logical test to be checked under the Case statement as follows.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")
Select Case usrInpt
Case Is < 100

End Sub

VBA Switch Case Example 1-4

Step 6: Use MsgBox function to add an output message if Case Is < 100 is true.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")
Select Case usrInpt
Case Is < 100
MsgBox "The provided number is less than 100"

End Sub

VBA Switch Case Example 1-5
Step 7: Now, we need to provide an executable statement when the value for usrInpt is greater than 100. Add a Case and MsgBox to achieve this.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")
Select Case usrInpt
Case Is < 100
MsgBox "The provided number is less than 100"
Case Is > 100
MsgBox "The provided number is greater than 100"

End Sub

VBA Switch Case Example 1-6

Step 8: What if the value provided by the user is exactly the 100? We have no case added for that. Let’s add the one that gives the user a message that the value he entered is 100.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")
Select Case usrInpt
Case Is < 100
MsgBox "The provided number is less than 100"
Case Is > 100
MsgBox "The provided number is greater than 100"
Case Is = 100
MsgBox "The provided number is 100"

End Sub

VBA Switch Case Example 1-7

Step 9: We need to end the Select Case statement. Use End Select to end the loop created.

Code:

Sub switch_case_example1()

Dim usrInpt As Integer
usrInpt = InputBox("Please enter your value")
Select Case usrInpt
Case Is < 100
MsgBox "The provided number is less than 100"
Case Is > 100
MsgBox "The provided number is greater than 100"
Case Is = 100
MsgBox "The provided number is 100"
End Select

End Sub

Use End Select Example 1-8

Step 10: Now, run this code by hitting the Run button or F5. A new popup box will appear asking for the value to be checked. I will enter a value as 110 and hit the OK button on the input box. Since the number I enter is greater than 100, as soon as I click on OK, a new message will pop-up on my screen saying, “The provided number is greater than 100”.

VBA Switch Case Output 1

VBA Switch Case – Example #2

Suppose we want to capture the grade of students based on their marks. See the steps below on how we can achieve this.

Step 1: Define a new sub-procedure named switch_case_example2.

Code:

Sub switch_case_example2()

End Sub

VBA Switch Case Example 2-1

Step 2: Define two new variables – marks as integer and grades as a string using Dim statement in the sub-procedure created.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String

End Sub

VBA Switch Case Example 2-2

Step 3: Use the VBA InputBox function through which the user can input the value for the variable marks.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")

End Sub

VBA InputBox function Example 2-3

Step 4: Use the Select Case statement and supply the variable marks as an expression to be checked.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks

End Sub

VBA Switch Case Example 2-4

Since we want to assign the grades to students based on the marks they input, we need to define the grades first.

Step 5: Use the case statement to check whether the marks are less than 35. If so, assign value as “F” to variable grades.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"

End Sub

VBA Switch Case Example 2-5

Step 6: If the marks are between 35 to 45, assign value as “D” to variable grades.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"

End Sub

VBA Switch Case Example 2-6

Step 7: If the marks inputted are between 46 to 55, value “C” should get assigned to variable grades.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"
Case 46 To 55
grades = "C"

End Sub

VBA Switch Case Example 2-7

Step 8: When the marks are in range 56 to 65, the value assigned to variable grades should be “B”.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"
Case 46 To 55
grades = "C"
Case 56 To 65
grades = "B"

End Sub

VBA Switch Case Example 2-8

Step 9: For marks between 66 to 75, the grade should be “A”.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"
Case 46 To 55
grades = "C"
Case 56 To 65
grades = "B"
Case 66 To 75
grades = "A"

End Sub

Marks between 66 to 75

Step 10: If the marks inputted are more than 75, grades variable should be assigned a value as “A+”

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"
Case 46 To 55
grades = "C"
Case 56 To 65
grades = "B"
Case 66 To 75
grades = "A"
Case Is > 75
grades = "A+"

End Sub

Marks More than 75

Step 11: Use End Select the close the Select Case loop.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"
Case 46 To 55
grades = "C"
Case 56 To 65
grades = "B"
Case 66 To 75
grades = "A"
Case Is > 75
grades = "A+"
End Select

End Sub

Use End Select Example 2-11

Step 12: Now, we need to check what is the grade associated with the marks a student has inputted. In order to achieve that, use MsgBox function in such a way that it denotes the achieved grades inside a message box.

Code:

Sub switch_case_example2()

Dim marks As Integer
Dim grades As String
marks = InputBox("Please enter the marks")
Select Case marks
Case Is < 35
grades = "F"
Case 35 To 45
grades = "D"
Case 46 To 55
grades = "C"
Case 56 To 65
grades = "B"
Case 66 To 75
grades = "A"
Case Is > 75
grades = "A+"
End Select
MsgBox "Grade achieved is: " & grades

End Sub

Use MsgBox function Example 2-12

Step 13: Run this code by hitting the F5 or Run button and you can see a VBA input box asking for a mark value. I will enter the marks as 72 and hit the OK button present on the input box. As soon as I hit the OK button inside the input box, I will get a message box indicating the grades associated with the marks entered.

VBA Switch Case Output 2

This is how we can use the Switch/Select Case statement inside VBA.

Things to Remember

  • Switch case is actually a synonym for Select Case statement in VBA. It has been called so because with the help of this statement we can switch between the different outputs at the same time.
  • This statement can be used as an alternative to the IF-Else loop whenever we have three or more conditions to check.
  • It is OK if you don’t use ELSE Case in Select Case statement. However, in that case, you need to make sure that at least one condition is true throughout the loop.

Recommended Articles

This is a guide to VBA Switch Case. Here we discuss How to Use the Switch Case Statement in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA IF Statements
  2. VBA Sort
  3. VBA While Loop
  4. VBA Environ

Switch Case or Select Case is a statement available in VBA to conduct logical tests where it works as an alternative to the IF-THEN statement in VBA. Using a Switch Case, we can conduct multiple logical tests and arrive at results based on multiple results.

Table of contents
  • Excel VBA Switch Case
    • How to Use VBA Switch Case Statement?
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • Recommended Articles

Below is the syntax of the Switch Case/Select Case statement.

Code:

Select Case < Logical Test >
Case 1 < Logical Test >
Value if Case 1 Test is TRUE
Case 2 < Logical Test >
Value if Case 2 Test is TRUE
Case 3 < Logical Test >
Value if Case 3 Test is TRUE
Case Else
Value if none of the above cases are TRUE
End Select

< Logical Test >: What is the logical test? We need to enter the test here.

Case 1, Case 2: We need to test multiple logical tests in excelA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more in each case.

How to Use VBA Switch Case Statement?

You can download this VBA Switch Case Excel Template here – VBA Switch Case Excel Template

Example #1

In cell A1 we have entered the value as 550.

VBA Switch Case Example 1

We will test this number using switch case statements and arrive at a “More than 500” status if the value exceeds 500. Else, we will arrive at the status of “Less than 500.”

Open the VBA Sub procedureSUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more first.

Code:

Sub Switch_Case()

End Sub

VBA Switch Case Example 1-1

Open Select Case Statement in VBAVBA Case Statement is a function that assists the users to execute multiple logical tests and arrive at results in two ways, i.e. first, if the result or logical test is TRUE and second, if the result or logical test is FALSE.read more and supply the logical test Range(“A2”).Value

Code:

Sub Switch_Case()

  Select CaseA select case is a substitute for writing down multiple IF statements in VBA. In the case of many IF statements, it becomes tedious and more complex, but in select case statements, we define the criteria as different cases and results.read more Range("A2").Value

End Sub

VBA Switch Case Example 1-2

Now, enter the first case as the Case is >500.

Code:

Sub Switch_Case()

  Select CaseA select case is a substitute for writing down multiple IF statements in VBA. In the case of many IF statements, it becomes tedious and more complex, but in select case statements, we define the criteria as different cases and results.read more Range("A2").Value
  Case Is > 500

End Sub

VBA Switch Case Example 1-3

If this case is TRUE, what is the result we need in cell B2? i.e., “More Than 500.”

Code:

Sub Switch_Case()

 Select Case Range("A2").Value
  Case Is > 500
   Range("B2").Value = "More than 500"

End Sub

VBA Switch Case Example 1-4

We left with only one result, i.e., Case Else statement. Therefore, if the first Case is FALSE, we need the result as “Less than 500.”

Code:

Sub Switch_Case()

 Select Case Range("A2").Value
  Case Is > 500
    Range("B2").Value = "More than 500"
  Case Else
    Range("B2").Value = "Less than 500"

End Sub

VBA Switch Case Example 1-5

Now, close the statement by using the “End Select” statement.

Code:

Sub Switch_Case()

 Select 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

VBA Switch Case Example 1-6

Run the code. We will get the value in cell B2.

VBA Switch Case Example 1-7

Since the value in cell A2 is greater than 500, we got the result of “More than 500.”

Example #2

Now, we will see using more case examples. Below is the score of the student in the examination.

Example 2

With this score, we need to arrive at a grade. For that, below is the criteria.

  • Score >=85, Grade = “Dist”
  • Score >=60, Grade = “First”
  • Score >=50, Grade = “Second”
  • Score >=35, Grade = “Pass”
  • If anything else Grade = “Fail.”

Code:

Sub Switch_Case1()

 Dim Score As Integer

 Score = 65

 Select 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 "Fail"
End Select

End Sub

Run this code. We will get the grade in the message box.

Example 2-1

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 the students.

Example 3

Since more than one student is involved, we need to enclose FOR NEXT loop in VBAAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more. Below is the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

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.

Example 3-1

Things to Remember

  • Often, Switch Case refers to as “Select Case.”
  • The switch is a functionSwitch function in excel is a comparison and referencing function which compares and matches a referred cell to a group of cells and returns the result based on the first match found. The method to use this function is =SWITCH( target cell, value 1, result 1….).read more, not a statement.
  • If no logical tests are TRUE, you can pass the alternative result in the CASE ELSE statement and always close the statement with the “END SELECT” word.

Recommended Articles

This article is a guide to VBA Switch Case. Here, we discuss switching-case statements in Excel VBA, examples, and downloadable Excel templates. Below are some useful articles related to VBA: –

  • Case Statement in Excel VBA
  • VBA UCase
  • Index Match in VBA
  • IF OR in VBA

The Select Case statement is an alternative way to write If/ElseIf statements.

You will find a Select Case statement equivalent in most popular programming languages. In many languages, the equivalent statement is the Switch statement. For example, the languages Java, C#, C++ and Javascript all have a switch statement.

Case Statement Quick Guide

Case Options Description Examples
Is Use with operators =, >,<,<>,>=,<= Case Is = 5
Case Is = «Apple»
Case Is > 5
Case Is <= 10
To Use for a range of numbers Case 5 To 10
Case 85 To 99
Case «A» To «D»
Comma Use the comma to include multiple conditions for one case Case 1, 3, 9, 11
Case 1, Is > 20, 10 To 15
No operator The same as «Is =» Case 5
Case «Apple»

Select Case Format

The format of the VBA Select Case statement is a follows:

Select Case [variable]
    Case [condition 1]
        [Statement 1]
    Case [condition 2]
        [Statement 2]
    Case [condition n]
        [Statement n]
    Case Else
        [Statement else]
End Select

The following is a simple example of using the Select Case Statement:

' https://excelmacromastery.com/
Public Sub Select_Case_Example()

    ' Read value from cell A1 on sheet1
    Dim airportCode As String
    airportCode = Sheet1.Range("A1").Value
    
    ' Print the name of the airport to the Immediate Window(Ctrl + G)
    Select Case airportCode
        Case "LHR"
            Debug.Print "London Heathrow"
        Case "JFK"
            Debug.Print "John F Kennedy"
        Case "SIN"
            Debug.Print "Singapore"
    End Select

End Sub

The code below is the equivalent If statement:

' https://excelmacromastery.com/
Public Sub If_Example()

    ' Read value from cell A1 on sheet1
    Dim airportCode As String
    airportCode = Sheet1.Range("A1").Value
    
    ' Print the name of the airport to the Immediate Window(Ctrl + G)
    If airportCode = "LHR" Then
            Debug.Print "London Heathrow"
    ElseIf airportCode = "JFK" Then
            Debug.Print "John F Kennedy"
    ElseIf airportCode = "SIN" Then
            Debug.Print "Singapore"
    End If

End Sub

We use the Select Case statement because it provides us with more flexibility than an If statement. We will see more above this below.

Using the Colon Operator

We can use the colon symbol “:” to make our Case statements look neater. The colon symbol allows us to place two lines VBA lines of code on one line. They are still treated as two lines by VBA but the code looks neater:

Select Case airportCode
    Case "LHR": Debug.Print "London Heathrow"
    Case "JFK": Debug.Print "John F Kennedy"
    Case "SIN": Debug.Print "Singapore"
End Select

Code Between Case Statements

In the previous examples we had just one line of code for each Case Condition. You can have as many lines of code as you want. However it is good practice to keep it to one line if possible. The purpose of the Select Case statement is to make the code readable.

In the following example, we have multiple lines of code for the Case “London”:

' https://excelmacromastery.com/
Sub MultiLine()

    Dim city As String
    city = Sheet1.Range("A1").Value

    Select Case city
        Case "London"
            ' would be better in another sub
            Count = Count + 1
            x = 6
            a = 5
        Case Else
            Debug.Print "other city"
    End Select
    
End Sub

If we have multiple lines, we could place them in a sub and then call this sub:

Select Case city
    Case "London"
        Call UpdateValues
    Case Else
        Debug.Print "other city"
End Select

Case Else

The Case Else statement is used with Select Case. It is the equivalent of the Else statement used with If. In simple terms, it means “if no other options were selected then select this one”.

Case Else is often used to check that a valid value was supplied. In the example below, it is used to check if the Airport Code was valid:

' https://excelmacromastery.com/
Public Sub Select_Case_Else()

    ' Read value from cell A1 on sheet1
    Dim airportCode As String
    airportCode = Sheet1.Range("A1").Value
    
    ' Print the name of the airport to the Immediate Window (Ctrl + G)
    Select Case airportCode
        Case "LHR"
            Debug.Print "London Heathrow"
        Case "JFK"
            Debug.Print "John F Kennedy"
        Case "SIN"
            Debug.Print "Singapore"
        Case Else
            MsgBox "The airport code is not valid.", vbInformation
    End Select

End Sub

Using Select Case with Numbers

We can use the To keyword to specify a range of numbers:

' https://excelmacromastery.com/
Select Case marks
    Case 85 To 100
        Debug.Print "High Distinction"
    Case 75 To 84
        Debug.Print "Distinction"
    Case 55 To 74
        Debug.Print "Credit"
    Case 40 To 54
        Debug.Print "Pass"
    Case Else
         Debug.Print "Fail"
End Select

Select Case Is

We can use the Is keyword if we want to use the operators like =, >,< etc.

In the below example, I have rewritten the previous Select Case statement using Is instead of To:

' https://excelmacromastery.com/
Select Case marks

    Case Is >= 85
        Debug.Print "High Distinction"
    Case Is >= 75
        Debug.Print "Distinction"
    Case Is >= 55
        Debug.Print "Credit"
    Case Is >= 40
        Debug.Print "Pass"
    Case Else
        ' For all other marks
        Debug.Print "Fail"
        
End Select

We don’t need to use the Is keyword when using equals. The two lines below are equivalent:

Case "LHR"
Case Is = "LHR"

So are these two:

Case 10
Case Is = 10

Select Case Multiple Values

We can have multiple case conditions on one line. We simply use the comma to separate them:

Case Is > 85, 70 To 75, 83
Case 2, 4, 6, 8
    Debug.Print "Even numbers"
Case 1, 3, 5, 7
    Debug.Print "Odd numbers"

The following is an example of using multiple strings:

' https://excelmacromastery.com/
Public Sub Select_Case_Multi()

    Dim city As String
    ' Change value to test
    city = "Dublin"
    
    ' Print the name of the airport based on the code
    Select Case city
        Case "Paris", "London", "Dublin"
            Debug.Print "Europe"
        Case "Singapore", "Hanoi"
            Debug.Print "Asia"
        Case Else
            MsgBox "The city is not valid.", vbInformation
    End Select

End Sub

Comparing Upper and Lower Case

We can use Option Compare at the top of the VBA module. This affects how strings are compared within that module.

We can use Binary or Text with Option Compare.

Option Compare Binary
Option Compare Text
  1. Binary means that VBA checks the case of the letters – case sensitive.
  2. Text means that VBA ignores the case of the letters – not case sensitive.

If we set “Option Compare Binary” then the following If and Case statements will evaluate to false.

If we set “Option Compare Text” they will evaluate to true:

city = "Dublin"

' true for "Option Compare Text"
' false for "Option Compare binary"
If city = "DUBLIN" Then
End If

Select Case city
    ' true for "Option Compare Text"
    ' false for "Option Compare binary"
    Case "DUBLIN"
End Select

You can try the following example. Change between Binary and Text and check the results:

' Change between "Binary" and "Text" and compare results
' https://excelmacromastery.com/
Option Compare Binary

Private Sub Select_Case_Multi()

    Dim city As String
    city = "dublin"
    
    ' Print the name of the airport based on the code to the
    ' Immediate Window (Ctrl + G).
    Select Case city
        Case "DUBLIN"
            Debug.Print "Europe"
        Case Else
            Debug.Print "The city is not valid."
    End Select

End Sub

Related Articles

VBA If Statement

VBA MessageBox

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    We can use Select case instead of using multiple if then statements in Excel VBA. In the below example user will enter the student mark in “Cell C5” as an input.  Macro read C5 cell value and fill grade in “Cell D5”.

    Grade:

    • <35 – Fail
    • 35-60 – Grade C
    • 60-80 – Grade B
    • >=80 – Grade A

    VBA Code read cell C5 value, use select case statement (apply criteria) and fill grade of a student.

    Declaring Variables:

    Variable  Data Type Comments
    mark  Integer read cell C5 Value
    result  String write in cell D5
    'variable declaration
    Dim mark As Integer, result As String

    Initialize variable

    'initialize variable
    mark = Range("C5").Value

    Select case… – check the mark variable and assign a respective grade to the variable result

    'select case statement to check mark and execute case statement
    Select Case mark
        Case Is >= 80
            result = "Grade A"
        Case Is >= 60
            result = "Grade B"
        Case Is >= 35
            result = "Grade C"
        Case Else
            result = "FAIL"
    End Select

    Write the Grade to cell D5

    Range("D5").Value = result

    Step 1: Just create a template like below

    Step 2: Add a shape “Update Grade”

    Step 3: Right-click on “Update Grade” and “Assign Macro..”

    Step 4: Select “updateGrade”, you can see a list of available macros in your workbook

    Step 5: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm

    Step 6: Click “Update Grade” to execute the VBA code and see the output in cell D5

    Outputs:

    Like Article

    Save Article

    Like this post? Please share to your friends:
  • Vba excel rows переменная
  • Vba excel range font color
  • Vba excel sub с параметрами
  • Vba excel rows диапазон
  • Vba excel range all rows