Vba excel select case and or

In this Excel VBA Select Case Or Tutorial, you learn how to create an Excel VBA Select Case Or statement to conditionally execute a set of statements based on:

  • An expression’s value, and
  • Whether this value matches any 1 of several values inside a single case expression (Value1 Or Value2 Or … Or Value#).

The Excel VBA Select Case Or snippet template/structure you learn in this Tutorial is a specific application of more general Excel VBA Select Case snippet templates/structures. You may (also) be interested in the following related snippet templates/structures:

  • Excel VBA Select Case Between 2 Values.
  • Excel VBA Select Case Multiple Values.
  • Excel VBA Select Case Multiple Conditions.
  • Excel VBA Select Case Multiple Test Expressions.

I link to these Tutorials in the Related Excel Macro and VBA Training Materials and Resources Section.

This Excel VBA Select Case Or Tutorial is accompanied by an Excel workbook with the data and VBA code I use. Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case Or example workbook

The VBA code in the Excel workbook that accompanies this Excel VBA Select Case Or Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section.

Related Excel Macro and VBA Training Materials and Resources

The following Excel Macro and VBA Tutorials may help you better understand and implement this VBA Select Case Or Tutorial.

  • Tutorials about general macro and VBA constructs and structures:
    • Tutorials for Beginners:
      • Excel Macros: Click here to open.
      • Excel VBA: Click here to open.
    • Enable macros in Excel: Click here to open.
    • Work with the Visual Basic Editor (VBE): Click here to open.
    • Create Sub procedures: Click here to open.
    • Work with:
      • Variables: Click here to open.
      • Data types: Click here to open.
      • Functions: Click here to open.
  • Tutorials with practical VBA applications and macro examples:
    • MsgBox: Click here to open.

This Excel VBA Select Case Or Tutorial is part of a more comprehensive series of Excel VBA Select Case Tutorials.

  • Excel VBA Select Case Tutorial: Click here to open.
  • Excel VBA Select Case Or: Click here to open.
  • Excel VBA Select Case And Operator: Click here to open.
  • Excel VBA Select Case Multiple Test Expressions: Click here to open.
  • Excel VBA Select Case Like Wildcard: Click here to open.
  • Excel VBA Select Case Inside For… Next Loop: Click here to open.
  • Excel VBA Select Case Range of Cells: Click here to open.

You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives. The following are some of my most popular Excel Tutorials and Training Resources:

  • Excel Keyboard Shortcuts Cheat Sheet: Click here to open.
  • Work with the Excel XLOOKUP Function: Click here to open.
  • Excel Power Query (Get & Transform) Tutorial for Beginners: Click here to open.

If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:

  • Premium Courses at the Power Spreadsheets Academy: Click here to open.
  • Books at the Power Spreadsheets Library: Click here to open.
  • VBA Cheat Sheets: Click here to open.

If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:

  • Code generators.
  • An extensive code library.
  • The ability to create your own code library.
  • Advanced coding tools.

If you need help with Excel tasks/projects, you may be interested in working with me: Click here to learn more about working with me.


Get immediate free access to the Excel VBA Select Case Or example workbook

Excel VBA Select Case Or Snippet Template/Structure

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case TestExpression
    Case Case11, Case12, ..., Case1#
        CaseStatements1
    Case Case21, Case22, ..., Case2#
        CaseStatements2
    '...
    Case Case#1, Case#2, ..., Case##
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case Or example workbook

Step-by-Step Process to Create an Excel VBA Select Case Or Statement

(1) Enter the opening and closing statements of the Select Case statement:

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case '...
    '...
End Select

(2) Specify the test expression VBA uses to identify the set of statements to execute.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case TestExpression
    '...
End Select

(3) Specify the case expressions used by VBA to identify the set of statements to execute. Each case expression is preceded by the Case keyword.

Use commas to separate multiple:

  • Values or strings; or
  • Value or string ranges (usually created by working with the To or Is keywords);

Inside a single case expression.

In other words: Use commas (instead of the Or operator) to create an Excel VBA Select Case Or statement that follows the template/structure you learn in this Excel VBA Select Case Or Tutorial.

  • Case Case11, Case12, …, Case1#
  • Case Case21, Case22, …, Case2#
  • Case Case31, Case32, …, Case3#

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case TestExpression
    Case Case11, Case12, ..., Case1#
        '...
    Case Case21, Case22, ..., Case2#
        '...
    '...
    Case Case#1, Case#2, ..., Case##
        '...
    '...
End Select

(4) Specify the set of statements to execute when the test expression (you specified in step #2) matches one of the values or strings (you specified in step #3) inside a case expression.

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case TestExpression
    Case Case11, Case12, ..., Case1#
        CaseStatements1
    Case Case21, Case22, ..., Case2#
        CaseStatements2
    '...
    Case Case#1, Case#2, ..., Case##
        CaseStatements#
    '...
End Select

(5) Specify the set of statements to execute if no value or string (you specified in step #3) inside a case expression matches the test expression (you specified in step #2). These catch-all statements:

  • Follow the Case Else keyword; and
  • Are optional.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case TestExpression
    Case Case11, Case12, ..., Case1#
        CaseStatements1
    Case Case21, Case22, ..., Case2#
        CaseStatements2
    '...
    Case Case#1, Case#2, ..., Case##
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case Or example workbook

How (and Why) the VBA Select Case Or Statement Works

The Select Case statement does the following:

  1. Compare a test expression to several case expressions.
  2. Determine how to proceed based on the case expression that matches the test expression.

You can use commas to separate multiple:

  • Values or strings; or
  • Value or string ranges (usually created by working with the To or Is keywords);

Inside a single case expression.

If the value returned by the test expression matches any 1 of several (comma-delimited) values inside a single case expression (Case#1, Case#2, …, Case##), the Select Case statement:

  1. Executes the set of statements associated to the applicable Case clause (whose case expression matches the test expression); and
  2. Exits the Select Case statement.

From this perspective, commas serve (functionally) a similar purpose to the Or operator.

In other words:

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Case#1, Case#2, ..., Case##

Is (in the context of an Excel VBA Select Case Or statement) functionally similar to:

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Case#1 Or Case#2 Or ... Or Case##

The Or operator (however) is a logical operator.

If you want to create an Excel VBA Select Case Or statement with the Or operator (instead of the VBA Select Case Or (with commas) statement you learn in previous Sections):

  • The test expression; and
  • All case expressions;

Must return a Boolean value (True or False) when evaluated. This ensures that (both) the test expression and all case expressions are of the same data type.

The resulting Excel VBA Select Case Or operator snippet template/structure is (therefore) fundamentally different to the Excel VBA Select Case Or (with commas) snippet template/structure you learn in previous Sections. The Excel VBA Select Case Or operator snippet template/structure requires you do the following:

  • Set the test expression to the Boolean value True.
  • Specify the case expressions as logical expressions (expressions that return True or False). You use logical operators (including Or) to build these logical expressions.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/vba-select-case-or/
Select Case True
    Case LogicalCaseExpression1
        CaseStatements1
    Case LogicalCaseExpression2
        CaseStatements2
    '...
    Case LogicalCaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select

In my opinion, the Excel VBA Select Case Or (with commas) snippet template/structure you learn in previous Sections is (as a general rule) more intuitive, readable, and flexible (vs. this alternative Excel VBA Select Case Or operator snippet template/structure).


Get immediate free access to the Excel VBA Select Case Or example workbook

The VBA Select Case Or example macro (below) displays a message box. The message inside the message box varies, depending on the current month.

I use a VBA Select Case Or statement to specify the proper message.

Sub SelectCaseOr()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/vba-select-case-or/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMsgBoxMessage As String
    
    'Assign string to the MyMsgBoxMessage variable depending on the current month
    Select Case Month(Date:=Date)
        Case 1, 2, 3: MyMsgBoxMessage = "It's Q1"
        Case 4, 5, 6: MyMsgBoxMessage = "It's Q2"
        Case 7, 8, 9: MyMsgBoxMessage = "It's Q3"
        Case 10, 11, 12: MyMsgBoxMessage = "It's Q4"
    End Select
    
    'Display message box with string held by the MyMsgBoxMessage variable
    MsgBox MyMsgBoxMessage

End Sub

The test expression inside the Excel VBA Select Case Or example macro (Month(Date:=Date)) returns an integer between 1 and 12.

The case expressions I specify inside the Excel VBA Select Case Or example macro (considering the above) are:

  • 1, 2, 3.
  • 4, 5, 6.
  • 7, 8, 9.
  • 10, 11, 12.

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case Or example macro. I execute this example macro (and create this screenshot) in July.

Excel VBA Select Case Or example macro results


Get immediate free access to the Excel VBA Select Case Or example workbook

Download the Excel VBA Select Case Or Example Workbook

This Excel VBA Select Case Or Tutorial is accompanied by an Excel workbook with the data and VBA code I use. Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case Or example workbook

The VBA code in the Excel workbook that accompanies this Excel VBA Select Case Or Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section.

Related Excel Macro and VBA Training Materials and Resources

The following Excel Macro and VBA Tutorials may help you better understand and implement this VBA Select Case Or Tutorial.

  • Tutorials about general macro and VBA constructs and structures:
    • Tutorials for Beginners:
      • Excel Macros: Click here to open.
      • Excel VBA: Click here to open.
    • Enable macros in Excel: Click here to open.
    • Work with the Visual Basic Editor (VBE): Click here to open.
    • Create Sub procedures: Click here to open.
    • Work with:
      • Variables: Click here to open.
      • Data types: Click here to open.
      • Functions: Click here to open.
  • Tutorials with practical VBA applications and macro examples:
    • MsgBox: Click here to open.

This Excel VBA Select Case Or Tutorial is part of a more comprehensive series of Excel VBA Select Case Tutorials.

  • Excel VBA Select Case Tutorial: Click here to open.
  • Excel VBA Select Case Or: Click here to open.
  • Excel VBA Select Case And Operator: Click here to open.
  • Excel VBA Select Case Multiple Test Expressions: Click here to open.
  • Excel VBA Select Case Like Wildcard: Click here to open.
  • Excel VBA Select Case Inside For… Next Loop: Click here to open.
  • Excel VBA Select Case Range of Cells: Click here to open.

You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives. The following are some of my most popular Excel Tutorials and Training Resources:

  • Excel Keyboard Shortcuts Cheat Sheet: Click here to open.
  • Work with the Excel XLOOKUP Function: Click here to open.
  • Excel Power Query (Get & Transform) Tutorial for Beginners: Click here to open.

If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:

  • Premium Courses at the Power Spreadsheets Academy: Click here to open.
  • Books at the Power Spreadsheets Library: Click here to open.
  • VBA Cheat Sheets: Click here to open.

If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:

  • Code generators.
  • An extensive code library.
  • The ability to create your own code library.
  • Advanced coding tools.

If you need help with Excel tasks/projects, you may be interested in working with me: Click here to learn more about working with me.


Get immediate free access to the Excel VBA Select Case Or example workbook

In this Article

  • Select Case Example
  • Case Statement Syntax
  • Select Case Criteria
    • Exact Match – Numbers
    • Ranges
    • Select Case Is
    • Case Else
  • Select Case – Text & the Like Operator
    • Exact Match – Text
    • Upper and Lower Case
    • Case Like
  • Case – Colon
  • Case Select – And / Or – Multiple Conditions
  • Nested Case Statements
  • Case Statement vs. If Statement
  • VBA Select Case Examples
  • VBA Select Case in Access

In VBA, the Select Case Statement is an alternative to the If-Then statement, allowing you to test if conditions are met, running specific code for each condition. The Select Statement is preferable to the If Statement when there are multiple conditions to process.

Select Case Example

This example prompts the user with a YesNoCancel MessageBox and tests which option the user selected:

Sub Select_Case_Yes_No_Cancel()
    Dim nResult As VbMsgBoxResult
    
    nResult = MsgBox("...", vbYesNoCancel)
    
    Select Case nResult
        Case vbYes
            MsgBox "Yes"
        Case vbNo
            MsgBox "No"
        Case vbCancel
            MsgBox "Cancel"
    End Select
End Sub

vba select case

Below we’ve written out the equivalent using an If Statement instead. You’ll notice that the Case Select Statement involves slightly less typing – this benefit is amplified when testing multiple criteria.

Sub If_Yes_No_Cancel()
    Dim nResult As VbMsgBoxResult
    
    nResult = MsgBox("...", vbYesNoCancel)
    
    If nResult = vbYes Then
        MsgBox "Yes"
    ElseIf nResult = vbNo Then
        MsgBox "No"
    ElseIf nResult = vbCancel Then
        MsgBox "Cancel"
    End If
End Sub

Case Statement Syntax

The Select Case Statement syntax is as follows:

Select Case [Test Expression]
    Case [Condition 1]
        [Action if condition 1 is true]
    Case [Condition 2]
        [Action if condition 2 is true]
    Case [Condition n]
        [Action if condition n is true]
    Case Else
        [Action if none are true]
End Select

Where:

[Test Expression] – Is the value to evaluate. Usually this is a variable.

[Action if condition n is true] – Is just the code to run if the condition is met (just like with an If Statement)

[Condition n] – Is the condition to test. There are a lot of different ways to test conditions. We will discuss them below.

The Case Statement will execute the code for the FIRST condition that is found to be TRUE.  If no condition is met then no code will be executed, unless the Else clause is added.

Select Case Criteria

Select Cases can be used to evaluate both numerical values and text.  First we will discuss how to use Select Cases to evaluate numerical expressions.

Exact Match – Numbers

You can easily test for an exact match with a Case Statement:

Case 10

or add commas to test for exact matches with multiple numbers:

Case 20, 30, 40
Sub ExactMatch_Numbers()
    Dim n As Integer
    n = CInt(InputBox("..."))
    
    Select Case n
        Case 10
            ' If n is 10 Then
        Case 20, 30, 40
            ' If n is 20/30/40 Then
        Case Else
            ' If n is not 10/20/30/40 Then
    End Select
    
End Sub

Ranges

You can test if a number falls within a range like so:

Case 55 To 74

This procedure will generate a letter score for a student based on their numerical score:

Sub Calc_Grade()
Dim Score       As Integer
Dim LetterGrade As String

    Score = InputBox("Enter Student Score")
    
    Select Case Score
        Case 90 To 100
            LetterGrade = "A"            
        Case 80 To 90
            LetterGrade = "B"           
        Case 70 To 80
            LetterGrade = "C"            
        Case 60 To 70
            LetterGrade = "D"            
        Case Else
            LetterGrade = "F"
    End Select
    
    MsgBox "The Student's Grade is: " & LetterGrade
    
End Sub

You can also test ranges with the Case Is

Select Case Is

Case is < 55
  'Do Nothing
Case <= 74
 MsgBox "In Range"

Remember that the Case Statement will only execute code for ONLY the first match.

This procedure will calculate a student’s grade using the Case Is instead of Case To.

Sub Select_Case_Is_Grade()
    Dim Score      As Integer
    Dim LetterGrade As String
    
    Score = InputBox("Enter Student Score")
    
    Select Case Score
        Case Is >= 90
            LetterGrade = "A"            
        Case Is >= 80
            LetterGrade = "B"            
        Case Is >= 70
            LetterGrade = "C"            
        Case Is >= 60
            LetterGrade = "D"            
        Case Else
            LetterGrade = "F"
    End Select
    
    MsgBox "The Student's Grade is: " & LetterGrade
    
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Case Else

You can add “Case Else” to the end of your Case Statement to do something if no conditions are met:

Case Else

See the end of the previous code example to see how Case Else can be used.

Select Case – Text & the Like Operator

So far our Select Case examples have worked only with numbers.  You can also use Select Case statements with text.

Exact Match – Text

You can test if the expression matches an exact phrase like this:

Case "Beets"

Or use commas to test if the expression exactly matches more than one phrase:

Case "Apple", "Banana", "Orange"

Putting it together looks like:

Sub ExactMatch_Food()

Select Case Range("a1").Value
    Case "Beets"
        MsgBox "Vegetable"
    Case "Apple", "Banana", "Orange"
        MsgBox "Fruit"
End Select

End Sub

VBA Programming | Code Generator does work for you!

Upper and Lower Case

By default, VBA is Case Sensitive. This means that VBA considers “Text” different than “text”. To turn case-sensitivity off add Option Compare Text to the top of your module:

Option Compare Text

This example will make the Case Select case-insensitive when working with text:

Option Compare Text

Sub ExactMatch_Food()

Select Case Range("a1").Value
    Case "Beets"
        MsgBox "Vegetable"
    Case "Apple", "Banana", "Orange"
        MsgBox "Fruit"
End Select

End Sub

Case Like

The Like Operator allows you to make inexact comparisons.  If the text matches, Like returns TRUE, if it doesn’t match it returns FALSE.  This makes the Like operator easy to use with If Statements, however it won’t work as easily with Case Statements.

Case Like – A Failed Test

The following code demonstrates that the Like Operator doesn’t work with Select Case:

Sub Select_Case_Like_DoesnotWork()
    Dim word As String
    word = "COCOA"
    
    Select Case word
        Case word Like "*C*C*"
            MsgBox "Good"
        Case Else
            MsgBox "Not Good"
    End Select
End Sub

Case Like – The Correct Way

However, we can add in the TRUE expression to make the Select Statement work with the Like Operator:

Sub Select_Case_Like_CorrectWay()
    Dim word As String
    word = "COCOA"
    
    Select Case True
        Case word Like "*C*C*"
            MsgBox "Good"
        Case Else
            MsgBox "Not Good"
    End Select
End Sub

Case – Colon

When using a Case Statement you can add as many lines of code as you’d like to run with each condition.  However, if you only need to run one line of code. You can use a Colon ( : ) to write everything on the same line.

Here is the same student grade example as before, except using a colon to shorten the code:

Sub Calc_Grade_colon()
Dim Score      As Integer
Dim LetterGrade As String

    Score = InputBox("Enter Student Score")
    
    Select Case Score
        Case 90 To 100: LetterGrade = "A"
        Case 80 To 90: LetterGrade = "B"
        Case 70 To 80: LetterGrade = "C"
        Case 60 To 70: LetterGrade = "D"
        Case Else: LetterGrade = "F"
    End Select
    
    MsgBox "The Student's Grade is: " & LetterGrade
    
End Sub

Case Select – And / Or – Multiple Conditions

You can use the And / Or Operators to test additional criteria along with the Select Case.

In this example we are using a Select Case on the variable ‘age’, but we also want to test sex. So we use the And Operator to perform the more complex test:

Sub NestedSelectCase()
    Dim sex As String
    Dim age As Integer
    
    sex = "male" ' or female
    age = 15
    
    Select Case age
        Case Is < 20 And sex = "male"
            Msgbox "Male under 20"
        Case Is < 20 And sex = "female"
            Msgbox "Female under 20"        
        Case Is >= 20 And sex = "male"
            Msgbox "Male over 20" 
        Case Is >= 20 And sex = "female"
            Msgbox "Female over 20" 
    End Select
End Sub

Nested Case Statements

Just like If Statements, you can nest Case Statements inside each other:

Sub NestedSelectCase()
    Dim sex As String
    Dim age As Integer
    
    sex = "male" ' or female
    age = 15
    
    Select Case age
        Case Is < 20
            Select Case sex
                Case "male"
                    MsgBox "Male under 20"
                Case "female"
                    MsgBox "Female under 20"
            End Select
        Case Is >= 20 And sex = "female"
            Select Case sex
                Case "male"
                    MsgBox "Male over 20"
                Case "female"
                    MsgBox "Female over 20"
            End Select
    End Select
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Case Statement vs. If Statement

The more conditions to test, the more useful the Case Statement is compared to an If Statement. Let’s look at an example.

Here is the code required to test if a worksheet name equals a set of values using an If Statement:

If Name = "Budget" Or Name = "Forecast" Or Name = "Trailing12" Or _
   Name = "Flex" Or Name = "OtherRatios" Or Name = "Comparison" Or _
   Name = "BudReview" Or Name = "P&L_Review" Or Name = "Other" Then
   'Do something
End If

Here is the same code using a Select Statement instead:

Select Case Name
Case "Budget", "Forecast", "Trailing12", "Flex", "OtherRatios", _
     "Comparison", "BudReview", "P&L_Review", "Other"
    'Do Something
End Select

You can see it’s much easier to use a Select Statement in this scenario. It’s significantly less typing, and it’s much easier to read.

VBA Select Case Examples

Ex 1. Case Statement User Defined Function (UDF)

Let’s replicate our grade calculation example above and create a UDF to calculate a student’s score:

Function GetGrade(Score As Integer) As String
    
    Select Case Score
        Case 90 To 100
            GetGrade = "A"            
        Case 80 To 90
            GetGrade = "B"            
        Case 70 To 80
            GetGrade = "C"            
        Case 60 To 70
            GetGrade = "D"           
        Case Else
            GetGrade = "F"
    End Select
    
End Function

Now we can use Function GetGrade in our Excel worksheet to quickly calculate student grades:

vba case select

Ex 2. Test Sheet Name / Loop Case Statement

This code will loop through all worksheets in a workbook, UnProtecting sheets that meet certain criteria:

Sub Case_UnProtectSheet()
    Dim ws As Worksheet
    
    For Each ws In Worksheets
        Select Case ws.Name    'List of all sheets with Ratios
        Case "Budget", "Forecast", "Trailing12", "Flex", "OtherRatios", _
             "Comparison", "BudReview", "P&L_Review", "Other"
            ws.Unprotect
        End Select
    Next ws
    
End Sub

Ex 3. Select Case – Cell Value

This example will test a student’s score in a cell, outputting the letter grade directly to the cell to the right.

Sub TestCellValue()
    Dim cell As Range
    Set cell = Range("C1")

    Select Case cell.Value
    Case 90 To 100
        cell.Offset(0, 1) = "A"
    Case 80 To 90
        cell.Offset(0, 1) = "B"
    Case 70 To 80
        cell.Offset(0, 1) = "C"
    Case 60 To 80
        cell.Offset(0, 1) = "D"
    End Select

End Sub

Ex 4. Select Case – Dates

This Case Select example is a Function that tests which quarter a date fall into.

Sub TestDate ()
 MsgBox GetQuarter(CDate("7/20/2019"))
End Sub

Function GetQuarter(dt As Date) As Integer
    Dim sht As Worksheet

    Select Case dt
        Case CDate("01/01/2019") To CDate("03/31/2019")
            GetQuarter = 1
        Case CDate("04/01/2019") To CDate("06/30/2019")
            GetQuarter = 2
        Case CDate("07/01/2019") To CDate("09/30/2019")
            GetQuarter = 3
        Case CDate("10/01/2019") To CDate("12/31/2019")
            GetQuarter = 4
    End Select
End Function

Because it’s a function, you can use it as a function inside Excel:

vba case select date example

Ex. 5 Check if Number is Odd or Even

This example tests if a number is odd or even.

Sub CheckOddEven()
    Dim n As Integer
    n = InputBox("Enter a number")
    
    Select Case n Mod 2
        Case 0
            MsgBox "The number is even."
        Case 1
            MsgBox "The number is odd."
    End Select
    
End Sub

Ex. 6 Test if Date is on Weekday or Weekend

These examples will test if a date falls on a weekday or a weekend.

Sub CheckWeekDay()
    Dim dt As Date
    dt = CDate("1/1/2020")
    
    Select Case Weekday(dt)
        Case vbMonday
            MsgBox "It's Monday"
        Case vbTuesday
            MsgBox "It's Tuesday"
        Case vbWednesday
            MsgBox "It's Wednesday"
        Case vbThursday
            MsgBox "It's Thursday"
        Case vbFriday
            MsgBox "It's Friday"
        Case vbSaturday
            MsgBox "It's Saturday"
        Case vbSunday
            MsgBox "It's Sunday"
    End Select
End Sub
Sub CheckWeekend()
    Dim dt As Date
    dt = CDate("1/1/2020")
    
    Select Case Weekday(dt)
        Case vbSaturday, vbSunday
            MsgBox "It's a weekend"
        Case Else
            MsgBox "It's not a weekend"
    End Select

End Sub

VBA Select Case in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Sub TestCellValue()
    Dim dbs as Database
    Dim rst as RecordSet
    Set dbs = CurrentDB
    Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
    With rst
       .MoveFirst
       .Edit
       Select Case rst.Fields("City")
       Case "Austin"
           .rst.Fields("TelCode") = "512" 
       Case "Chicago"
           .rst.Fields("TelCode") = "312" 
       Case "New YorK"
           .rst.Fields("TelCode") = "1212" 
       Case "San Fransisco"
           .rst.Fields("TelCode") = "415" 
    End Select
    .Update
   End With
End Sus

Оператор 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 выглядит изящней.

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.)

Содержание

  1. VBA Excel. Оператор Select Case (синтаксис, примеры)
  2. Описание оператора Select Case
  3. Синтаксис оператора Select Case
  4. Компоненты оператора Select Case
  5. Примеры использования в VBA Excel
  6. Пример 1
  7. Excel VBA Select Case Or in 5 Easy Steps (+ Free Easy-To-Adjust Excel Workbook Example)
  8. Related Excel Macro and VBA Training Materials and Resources
  9. Excel VBA Select Case Or Snippet Template/Structure
  10. Step-by-Step Process to Create an Excel VBA Select Case Or Statement
  11. How (and Why) the VBA Select Case Or Statement Works
  12. Excel VBA Select Case Or Example Macro
  13. Download the Excel VBA Select Case Or Example Workbook
  14. Related Excel Macro and VBA Training Materials and Resources

VBA Excel. Оператор Select Case (синтаксис, примеры)

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

Описание оператора Select Case

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

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

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

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

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

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

Пример 1

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

Источник

Excel VBA Select Case Or in 5 Easy Steps (+ Free Easy-To-Adjust Excel Workbook Example)

In this Excel VBA Select Case Or Tutorial, you learn how to create an Excel VBA Select Case Or statement to conditionally execute a set of statements based on:

  • An expression’s value, and
  • Whether this value matches any 1 of several values inside a single case expression (Value1 Or Value2 Or … Or Value#).

The Excel VBA Select Case Or snippet template/structure you learn in this Tutorial is a specific application of more general Excel VBA Select Case snippet templates/structures. You may (also) be interested in the following related snippet templates/structures:

  • Excel VBA Select Case Between 2 Values.
  • Excel VBA Select Case Multiple Values.
  • Excel VBA Select Case Multiple Conditions.
  • Excel VBA Select Case Multiple Test Expressions.

I link to these Tutorials in the Related Excel Macro and VBA Training Materials and Resources Section.

This Excel VBA Select Case Or Tutorial is accompanied by an Excel workbook with the data and VBA code I use. Get this example workbook (for free) by clicking the button below.

The VBA code in the Excel workbook that accompanies this Excel VBA Select Case Or Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section.

Table of Contents

The following Excel Macro and VBA Tutorials may help you better understand and implement this VBA Select Case Or Tutorial.

  • Tutorials about general macro and VBA constructs and structures:
    • Tutorials for Beginners:
      • Excel Macros: Click here to open.
      • Excel VBA: Click here to open.
    • Enable macros in Excel: Click here to open.
    • Work with the Visual Basic Editor (VBE): Click here to open.
    • Create Sub procedures: Click here to open.
    • Work with:
      • Variables: Click here to open.
      • Data types: Click here to open.
      • Functions: Click here to open.
  • Tutorials with practical VBA applications and macro examples:
    • MsgBox: Click here to open.

This Excel VBA Select Case Or Tutorial is part of a more comprehensive series of Excel VBA Select Case Tutorials.

  • Excel VBA Select Case Tutorial: Click here to open.
  • Excel VBA Select Case Or: Click here to open.
  • Excel VBA Select Case And Operator: Click here to open.
  • Excel VBA Select Case Multiple Test Expressions: Click here to open.
  • Excel VBA Select Case Like Wildcard: Click here to open.
  • Excel VBA Select Case Inside For… Next Loop: Click here to open.
  • Excel VBA Select Case Range of Cells: Click here to open.

You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives. The following are some of my most popular Excel Tutorials and Training Resources:

  • Excel Keyboard Shortcuts Cheat Sheet: Click here to open.
  • Work with the Excel XLOOKUP Function: Click here to open.
  • Excel Power Query (Get & Transform) Tutorial for Beginners: Click here to open.

If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:

  • Premium Courses at the Power Spreadsheets Academy: Click here to open.
  • Books at the Power Spreadsheets Library: Click here to open.
  • VBA Cheat Sheets: Click here to open.

If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:

  • Code generators.
  • An extensive code library.
  • The ability to create your own code library.
  • Advanced coding tools.

If you need help with Excel tasks/projects, you may be interested in working with me: Click here to learn more about working with me.

Excel VBA Select Case Or Snippet Template/Structure

Step-by-Step Process to Create an Excel VBA Select Case Or Statement

(1) Enter the opening and closing statements of the Select Case statement:

(2) Specify the test expression VBA uses to identify the set of statements to execute.

(3) Specify the case expressions used by VBA to identify the set of statements to execute. Each case expression is preceded by the Case keyword.

Use commas to separate multiple:

  • Values or strings; or
  • Value or string ranges (usually created by working with the To or Is keywords);

Inside a single case expression.

In other words: Use commas (instead of the Or operator) to create an Excel VBA Select Case Or statement that follows the template/structure you learn in this Excel VBA Select Case Or Tutorial.

  • Case Case11, Case12, …, Case1#
  • Case Case21, Case22, …, Case2#
  • Case Case31, Case32, …, Case3#

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

(4) Specify the set of statements to execute when the test expression (you specified in step #2) matches one of the values or strings (you specified in step #3) inside a case expression.

(5) Specify the set of statements to execute if no value or string (you specified in step #3) inside a case expression matches the test expression (you specified in step #2). These catch-all statements:

  • Follow the Case Else keyword; and
  • Are optional.

How (and Why) the VBA Select Case Or Statement Works

The Select Case statement does the following:

  1. Compare a test expression to several case expressions.
  2. Determine how to proceed based on the case expression that matches the test expression.

You can use commas to separate multiple:

  • Values or strings; or
  • Value or string ranges (usually created by working with the To or Is keywords);

Inside a single case expression.

If the value returned by the test expression matches any 1 of several (comma-delimited) values inside a single case expression (Case#1, Case#2, …, Case##), the Select Case statement:

  1. Executes the set of statements associated to the applicable Case clause (whose case expression matches the test expression); and
  2. Exits the Select Case statement.

From this perspective, commas serve (functionally) a similar purpose to the Or operator.

Is (in the context of an Excel VBA Select Case Or statement) functionally similar to:

The Or operator (however) is a logical operator.

If you want to create an Excel VBA Select Case Or statement with the Or operator (instead of the VBA Select Case Or (with commas) statement you learn in previous Sections):

  • The test expression; and
  • All case expressions;

Must return a Boolean value (True or False) when evaluated. This ensures that (both) the test expression and all case expressions are of the same data type.

The resulting Excel VBA Select Case Or operator snippet template/structure is (therefore) fundamentally different to the Excel VBA Select Case Or (with commas) snippet template/structure you learn in previous Sections. The Excel VBA Select Case Or operator snippet template/structure requires you do the following:

  • Set the test expression to the Boolean value True.
  • Specify the case expressions as logical expressions (expressions that return True or False). You use logical operators (including Or) to build these logical expressions.

In my opinion, the Excel VBA Select Case Or (with commas) snippet template/structure you learn in previous Sections is (as a general rule) more intuitive, readable, and flexible (vs. this alternative Excel VBA Select Case Or operator snippet template/structure).

Excel VBA Select Case Or Example Macro

The VBA Select Case Or example macro (below) displays a message box. The message inside the message box varies, depending on the current month.

I use a VBA Select Case Or statement to specify the proper message.

The test expression inside the Excel VBA Select Case Or example macro (Month(Date:=Date)) returns an integer between 1 and 12.

The case expressions I specify inside the Excel VBA Select Case Or example macro (considering the above) are:

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case Or example macro. I execute this example macro (and create this screenshot) in July.

Download the Excel VBA Select Case Or Example Workbook

This Excel VBA Select Case Or Tutorial is accompanied by an Excel workbook with the data and VBA code I use. Get this example workbook (for free) by clicking the button below.

The VBA code in the Excel workbook that accompanies this Excel VBA Select Case Or Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section.

The following Excel Macro and VBA Tutorials may help you better understand and implement this VBA Select Case Or Tutorial.

  • Tutorials about general macro and VBA constructs and structures:
    • Tutorials for Beginners:
      • Excel Macros: Click here to open.
      • Excel VBA: Click here to open.
    • Enable macros in Excel: Click here to open.
    • Work with the Visual Basic Editor (VBE): Click here to open.
    • Create Sub procedures: Click here to open.
    • Work with:
      • Variables: Click here to open.
      • Data types: Click here to open.
      • Functions: Click here to open.
  • Tutorials with practical VBA applications and macro examples:
    • MsgBox: Click here to open.

This Excel VBA Select Case Or Tutorial is part of a more comprehensive series of Excel VBA Select Case Tutorials.

  • Excel VBA Select Case Tutorial: Click here to open.
  • Excel VBA Select Case Or: Click here to open.
  • Excel VBA Select Case And Operator: Click here to open.
  • Excel VBA Select Case Multiple Test Expressions: Click here to open.
  • Excel VBA Select Case Like Wildcard: Click here to open.
  • Excel VBA Select Case Inside For… Next Loop: Click here to open.
  • Excel VBA Select Case Range of Cells: Click here to open.

You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives. The following are some of my most popular Excel Tutorials and Training Resources:

  • Excel Keyboard Shortcuts Cheat Sheet: Click here to open.
  • Work with the Excel XLOOKUP Function: Click here to open.
  • Excel Power Query (Get & Transform) Tutorial for Beginners: Click here to open.

If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:

  • Premium Courses at the Power Spreadsheets Academy: Click here to open.
  • Books at the Power Spreadsheets Library: Click here to open.
  • VBA Cheat Sheets: Click here to open.

If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:

  • Code generators.
  • An extensive code library.
  • The ability to create your own code library.
  • Advanced coding tools.

If you need help with Excel tasks/projects, you may be interested in working with me: Click here to learn more about working with me.

Источник

Key Points

  • With SELECT CASE, you can test multiple conditions, especially when you are working on more than two.
  • The code you write with SELECT CASE is way more structured than standard conditional code.
  • It is easier to modify it when you need to adjust one or more of the values in the code.

What is VBA Select Case

VBA SELECT CASE is a statement to test multiple conditions. In this statement, you can specify one condition and then specify a code to execute if that condition is true and then specify a second condition and a code to run if that condition is true. In this way, you can specify multiple conditions and multiple statements.

The syntax for select case

Below is the syntax that you need to follow to write a select case statement.

Select Case Test Expression

	Case (Condition to Test)
	Statement1 [Line of Code to Run if CASE 1 is TRUE]

	Case (Condition to Test)
	Statement1 [Line of Code to Run if CASE 2 is TRUE]

	Case Else
	Statement [Line of Code to Run if no CASE is TRUE]

End Select

In SELECT CASE syntax starts with the keyword “Select” and ends with “End Select”. To understand its syntax, we need to split it into four parts:

  • In the FIRST part, you need to specify the “Test Expression” on which all the conditions get tests.
  • After that, in the SECOND part, you need to specify the case to test (that means condition to test).
  • Now in the THIRD part, you need to write another case where you need to test if the condition in the second part is not TRUE.
  • In the end, in the FOURTH part, you need to specify an outcome that should come when both the above cases are not TRUE.

A simple example to understand a select case statement

The syntax of the SELECT CASE is self-explanatory and quite easy to follow while writing code. But let’s take an example and understand it completely. Below you have a simple code to test the value from cell A1.

Sub SelectCaseExample1()

    Select Case Range("A1").Value

        Case "Yes"
            MsgBox "It's a Yes."

        Case "No"
            MsgBox "It's a No"

        Case Else
            MsgBox "Can't Say"  
      
    End Select

End Sub

Now let’s understand this code with each line:

  • FIRST, you have the SELECT CASE keyword and the cell A1 to use as an expression for testing the condition.
  • SECOND, you have the keyword CASE and the condition (“YES”) to check from cell A1 and code to show a message box with the message “It’s a Yes” if the condition mentioned in the case1 is true.
  • THIRD, you again have the keyword case and the condition (“No”) to check from cell A1 and code to show a message box with the message “It’s a No” if the condition mentioned in case two is true.
  • FOURTH, you have the keyword CASE ELSE and a line of code to show a message box with a message “Can’t Say” if none of the cases are true.
  • FIFTH, you have the END SELECT keyword to end the SELECT CASE statement.

Related: VBA MESSAGE BOX

Important Points

  • It can test multiple conditions and execute a line of code based on the result.
  • You can use comparison operators (=, >, <, <>, >=, <=) while testing for a condition by using the Is keyword.
  • You can use a comma to test more than one condition within a single case.
  • You can also use a range of numbers while testing a condition in a single case.
  • When one condition is met, VBA stops to test the rest of the cases from the statement.
  • You can also add a case else section at the end to execute a line of code when none of the conditions are met.
  • You can skip using the CASE END statement.

More Examples to use Select Case

It’s time to use the SELECT CASE in different ways, and below are some of the useful and essential examples that you can learn.

100 Excel Macro Examples

1. Select Case with Numbers

While writing a VBA code for the SELECT CASE statement, you can use operators to compare values. Now in the below code, you have >,<, and = operators to test the conditions.

Sub SelectCaseExample1()

    Select Case Range("A1").Value

        Case Is >= 45
            MsgBox "Pass"    

        Case Is < 45
            MsgBox "Fail"    
   
    End Select

End Sub    
  • The first case in this statement checks if the value from cell A1 is greater than or equal to 45 or not and returns a message box with the message “Pass”.
  • And the second case in the statement checks if the value from cell A1 is lower than 45 and returns a message box with the message “Fail”. 

2. Select Case with a Range of Numbers

You can also use a range of numbers to test a condition. In the below code, you have a condition with a range of numbers in each case to test.

Sub SelectCaseExample2()

    Select Case Range(“A1”).Value

        Case 45 To 100
            MsgBox “Pass”    
    
        Case 0 To 44
            MsgBox “Fail”       

        Case Else
            MsgBox “Out of Range”           

    End Select   

End Sub
  • The first case in the statement checks the number from cell A1 using the range of numbers from 45 to 100 and returns the “Pass” if the value falls under this range.
  • The second statement has a range of 0 to 44 to test with the value from cell A1 and returns “Fail” if the value falls under this range.
  • The third statement is case else show a message box with the message “Out of Range” if cases one and two are false.

3. Using the Colon Operator

While writing code for the SELECT CASE, you can use colon operators to write the entire case in one line.

In the below code, the line starts with the case and then the condition to test and then a colon, and then the statement to run in that case is true.

Sub SelectCaseExample3()

    Select Case Range(“A1”).Value   

        Case 45 To 100: MsgBox “Pass”           

        Case 0 To 44: MsgBox “Fail”           

        Case Else: MsgBox “Out of Range”           

    End Select   

End Sub

4. Use Select Case with Multiple Conditions

Just like defining a range for a case, you can also specify multiple values to test for the condition. In the below code, each case has three numbers to test.

Sub SelectCaseExample()

    Select Case Range("A1").Value

        Case 1, 3, 5
            MsgBox "Yes"
            
        Case 2, 4, 6
            MsgBox "No"
            
        Case Else
            MsgBox "Out of range"
            
    End Select
        
End Sub
  • The first case of this code will test the value from the cell if it is 1, 3, or 5 and will return “Yes” in a message box.
  • And the second case of this code will test the value from cell A1 if it’s 2, 4, or 6.

5. Using Select Case in a Custom Function

You can also use the SELECT CASE while writing code for a VBA Function.

Function udfGrade(student_marks As Integer)

Dim myGrade As String

Select Case student_marks

    Case Is < 40: myGrade = “Bad”

    Case 41 To 50: myGrade = “Average”

    Case 51 To 60: myGrade = “Good”

    Case 61 To 80: myGrade = “Very Good”   

    Case 81 To 100: myGrade = “Excellent”

End Select

udfGrade = myGrade

End Function

In the above function, it has five cases to check for the score of the students from a cell. All 5 cases use a range of numbers and return the value defined in the statement.

6. Using Select Case from Nested Conditions

You can also create a nested condition statement. What I’m trying to say is you can write a code to test multiple conditions with the select case.

Imagine if you want to write a code that can test conditions based on the values from two different cells.

Sub SelectCaseStatement()

    Select Case Range("A2")
    
        Case "Boy"
        
            Select Case Range("B2")
                Case "Commerce": MsgBox "Boy (Commerce)"
                Case "Science": MsgBox "Boy (Science)"
            End Select
            
        Case "Girl"
        
            Select Case Range("B2")
                Case "Commerce": MsgBox "Girl (Commerce)"
                Case "Science": MsgBox "Girl (Science)"
            End Select
            
    End Select
    
End Sub

In the above code, you have three select case statements. There is one main statement that checks for the value from the cell A2 if it is “Boy” or “Girl”.

And then, based on the result, two more statements run and check for the value from cell B2 if it is Commerce or Science.

SELECT CASE Vs. IF THEN ELSE Statement

  • When you want to test multiple conditions, it’s easy to write a code using the SELECT CASE instead of IF-THEN.
  • Even it is easy to edit and make changes in a SELECT CASE statement compared to IF-THEN.

Excel VBA has the IF Then Else construct that you can use to analyze multiple conditions and execute codes based on these conditions.

Another similar construct that allows you to check for multiple conditions is the SELECT CASE statement.

Select Case is useful when you have three or more conditions that you want to check. You can also use this with two conditions (but I feel If Then Else is easier to use in those cases).

A simple example where the Select Case statement is useful when you want to get the grade of a student based on the marks he/she has scored (covered as an example later in this tutorial).

Note: All the example codes covered in this tutorial are meant to be placed in a module in VBA.

Select Case Syntax

Below is the syntax of Select Case in Excel VBA:

Select Case Test_Expression

Case Value_1
Code Block when Test_Expression = Value_1

Case Value_2
Code Block when Test_Expression = Value_2

Case Value_3
Code Block when Test_Expression = Value_3

Case Else
Code Block when none of the case conditions are met

End Select
  • Test_Expression: This is the expression whose value we analyze by using different cases (explained better with the examples below).
  • Condition_1, Condition_2,…: These are the conditions on which the text expression is tested. If it meets the condition, then the code block for the given condition is executed.

For every Select Case statement that you use, you need to use the End Select statement.

Note: As soon as a condition is met, VBA exits the select case construct. So if you have five conditions, and the second condition is met, VBA would exit Select Case – and the rest of the conditions will not be tested.

Select Case Examples

Now to better understand how to use Select Case statement in VBA, let’s go through a few examples.

Note that most of the examples in this tutorial are meant to explain the concept. These may or may not be the best way to get the work done.

Let’s start with a simple example of see how Select Case allows us to check for conditions.

Example 1 – Check the Numbers

In the below example, the code asks the user to enter any number between 1 and 5, and then shows a message box with the number the user entered.

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number between 1 and 5")

Select Case UserInput

Case 1
MsgBox "You entered 1"

Case 2
MsgBox "You entered 2"

Case 3
MsgBox "You entered 3"

Case 4
MsgBox "You entered 4"

Case 5
MsgBox "You entered 5"

End Select
End Sub

Note that this code is far from useful and is not even foolproof. For example, if you enter 6 or any string, it would do nothing. But as I mentioned, my intent here is to showcase how Select Case works.

Example 2 – Using Select Case with IS Condition

You can use an IS condition with the Select Case construct to check for the value of numbers.

The below code checks whether the input number is greater than 100 or not.

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number")

Select Case UserInput

Case Is < 100
MsgBox "You entered a number less than 100"

Case Is >= 100
MsgBox "You entered a number more than (or equal to) 100"

End Select
End Sub

Example 3 – Using Case Else to Catch All

In the above example, I used two conditions (less than 100 or greater than or equal to 100).

Instead of the second case with a condition, you can also use Case Else.

Case Else acts as a catch-all and anything which doesn’t fall into any of the previous cases is treated by the Case Else.

Below is an example code where I have used Case Else:

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number")

Select Case UserInput

Case Is < 100
MsgBox "You entered a number less than 100"

Case Else
MsgBox "You entered a number more than (or equal to) 100"

End Select
End Sub

Example 4 – Using a Range of Numbers

In Select Case, you can also check for a range of numbers.

The below code asks for an input and shows a message box based on the value.

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number between 1 and 100")

Select Case UserInput

Case 1 To 25
MsgBox "You entered a number less than 25"

Case 26 To 50
MsgBox "You entered a number between 26 and 50"

Case 51 To 75
MsgBox "You entered a number between 51 and 75"

Case 75 To 100
MsgBox "You entered a number more than 75"

End Select
End Sub

Example 5 – Get the Grade based on the Marks Scored

So far we have seen basic examples (which are not really useful in the practical world).

Here is an example which is closer to a real-world example where you can use Select Case in Excel VBA.

The following code will give you the grade a student gets based on the marks in an exam.

Sub Grade()
Dim StudentMarks As Integer
Dim FinalGrade As String
StudentMarks = InputBox("Enter Marks")

Select Case StudentMarks

Case Is < 33
FinalGrade = "F"

Case 33 To 50
FinalGrade = "E"

Case 51 To 60
FinalGrade = "D"

Case 60 To 70
FinalGrade = "C"

Case 70 To 90
FinalGrade = "B"

Case 90 To 100
FinalGrade = "A"

End Select
MsgBox "The Grade is " & FinalGrade

End Sub

The above code asks the user for the marks and based on it, shows a message box with the final grade.

In the above code, I have specified all the conditions – for marks 0 – 100.

Another way to use Select Case is to use a Case Else at the end. This is useful when you have accounted for all the conditions and then specify what to do when none of the conditions is met.

The below code is a variation of the Grade code with a minor change. In the end, it has a Case else statement, which will be executed when none of the above conditions are true.

Sub CheckOddEven()
Dim StudentMarks As Integer
Dim FinalGrade As String
StudentMarks = InputBox("Enter Marks")
Select Case StudentMarks
Case Is < 33
FinalGrade = "F"

Case 33 To 50
FinalGrade = "E"

Case 51 To 60
FinalGrade = "D"

Case 60 To 70
FinalGrade = "C"

Case 70 To 90
FinalGrade = "B"

Case Else
FinalGrade = "A"

End Select
MsgBox "The Grade is " & FinalGrade

End Sub

Example 6 – Creating a Custom Function (UDF) using Select Case

In the above example, the code asked the user for the marks input.

You can also create a custom function (User Defined Function) that can be used just like any regular worksheet function, and which will return the grade of the students.

Below is the code that will create the custom formula:

Function GetGrade(StudentMarks As Integer)
Dim FinalGrade As String

Select Case StudentMarks

Case Is < 33
FinalGrade = "F"

Case 33 To 50
FinalGrade = "E"

Case 51 To 60
FinalGrade = "D"

Case 60 To 70
FinalGrade = "C"

Case 70 To 90
FinalGrade = "B"

Case Else
FinalGrade = "A"

End Select
GetGrade = FinalGrade

End Function

Once you have this code in the module, you can use the function GetGrade in the worksheet as shown below.

Select Case Statement in Excel VBA - Get Grade Custom Function

Example 7 – Check ODD / EVEN with Select Case

Below is an example code where I check whether the number in cell A1 is odd or even.

Sub CheckOddEven()
CheckValue = Range("A1").Value

Select Case (CheckValue Mod 2) = 0

Case True
MsgBox "The number is even"

Case False
MsgBox "The number is odd"

End Select
End Sub

Example 8 – Checking for Weekday/Weekend (Multiple Conditions)

You can also use Select Case to check for multiple values in the same case.

For example, the below code uses the current date to show whether today is a weekday or weekend (where weekend days are Saturday and  Sunday)

Sub CheckWeekday()
Select Case Weekday(Now)

Case 1, 7
MsgBox "Today is a Weekend"

Case Else
MsgBox "Today is a Weekday"

End Select
End Sub

In the above code, we check for two conditions (1 and 7) in the same case.

Note: Weekday function returns 1 for Sunday and 7 for Saturday.

Example 9 – Nested Select Case Statements

You can also nest one Select Case statement within other.

Below is a code that checks whether a day is a weekday or a weekend, and if it’s a weekend, then it will display whether it’s a Saturday or a Sunday.

Sub CheckWeekday()
Select Case Weekday(Now)

Case 1, 7
   Select Case Weekday(Now)
   Case 1
      MsgBox "Today is Sunday"
   Case Else
      MsgBox "Today is Saturday"
  End Select

Case Else
MsgBox "Today is a Weekday"
End Select
End Sub

In the above code, I have nested the Select Case to check whether the weekend is a Saturday or a Sunday.

Note: The example shown above is to explain the concept. This is not the best or the most practical way to find out weekday/weekend.

Example 10 – Checking Text String with Select Case

You can check specific strings using Select Case and then execute code based on it.

In the example code below, it asks the user to enter their department name and shows the name of the person they should connect with for onboarding.

Sub OnboardConnect()
Dim Department As String
Department = InputBox("Enter Your Department Name")

Select Case Department

Case "Marketing"
MsgBox "Please connect with Bob Raines for Onboarding"

Case "Finance"
MsgBox "Please connect with Patricia Cruz for Onboarding"

Case "HR"
MsgBox "Please connect with Oliver Rand for Onboarding"

Case "Admin"
MsgBox "Please connect with Helen Hume for Onboarding"

Case Else
MsgBox "Please connect with Tony Randall for Onboarding"

End Select
End Sub

Hope all the examples above were helpful in understanding the concept and application of Select Case in Excel VBA.

You May Also Like the Following VBA Tutorials:

  • Excel VBA Loops – For Next, Do While, Do Until, For Each.
  • For Next Loop in Excel VBA.
  • How to Record a Macro in Excel.

New to VBA. I’m attempting to build a value of Dimensions (pulling from two different cells in an excel spreadsheet in which one might be larger than the other, and I always want the lower number first) in which the output (a string which will be concatenated with strings from other functions) might be one of the following:

4868 (no x separating the integer values)
48×60.5 (with x separating an integer and real number)
36.5×60 (with x separating a real number and an integer)
24.75×72.125 (with x separating a real number and an integer)

Variable types are defined in VBA as Single (not Double). Here’s my code:

Function getDimDisplay(h As Single, w As Single) As String

Dim strResult As String
Dim iH As Integer
Dim iW As Integer
Dim strH As Variant
Dim strW As Variant

iH = CInt(h)
iW = CInt(w)

Select Case h
    Case (h >= w And iH = h And iW = w)
        strH = CStr(iH)
        strW = CStr(iW)
        strResult = strW & strH
    Case (h >= w And iH <> h And iW = w)
        strH = CStr(h)
        strW = CStr(iW)
        strResult = strW & "x" & strH
    Case (w >= h And iH = h And iW <> w)
        strH = CStr(iH)
        strW = CStr(w)
        strResult = strH & "x" & strW
    Case (w >= h And iH <> h And iW <> w)
        strH = CStr(h)
        strW = CStr(w)
        strResult = strH & "x" & strW
End Select

getDimDisplay = strResult

End Function

It will compile, but it won’t return any output. What gives?

Automate This's user avatar

asked Jan 23, 2014 at 21:33

user3229658's user avatar

3

your variable ‘h’ is not a boolean. However, you’re calling it in select case to match conditions which are either true or false.

Change your «select case h» to «select case true». all else will work ok.

Select Case True

Case (h >= w And iH = h And iW = w)
    strH = CStr(iH)
    strW = CStr(iW)
    strResult = strW & strH
Case (h >= w And iH <> h And iW = w)
    strH = CStr(h)
    strW = CStr(iW)
    strResult = strW & "x" & strH
Case (w >= h And iH = h And iW <> w)
    strH = CStr(iH)
    strW = CStr(w)
    strResult = strH & "x" & strW
Case (w >= h And iH <> h And iW <> w)
    strH = CStr(h)
    strW = CStr(w)
    strResult = strH & "x" & strW

End Select

answered Sep 25, 2018 at 19:39

Michael James's user avatar

Michael JamesMichael James

4621 gold badge6 silver badges18 bronze badges

Select Case doesn’t work like this. It compares the item presented (h) to the values calculated for the individual case statements.

The case statements you have all evaluate to a bool, true or fasle. Whatever h equals, it’s not that! For this bit of code, you nedd an if then else if structure.

answered Jan 24, 2014 at 9:02

simon at rcl's user avatar

simon at rclsimon at rcl

7,2611 gold badge17 silver badges24 bronze badges

1

Just for completeness, the closest you can get to the structure youre looking for is this type of thing:

Select Case h
Case Is >= w And Is = iH
    If w = iW Then
    '   do stuff
    Else
    '   do other stuff
    End If
Case Is <= w And Is = iH
    If w <> iW Then
    '   do stuff
    End If
Case Is > -w And Is <> iH
    If w <> iW Then
    '   do stuff
    End If
End Select

answered Jan 30, 2014 at 0:19

Cool Blue's user avatar

Cool BlueCool Blue

6,4286 gold badges28 silver badges67 bronze badges

2

try this:

Function getDimDisplay(h As Single, w As Single) As String
Dim iH%:    iH = CInt(h)
Dim iW%:    iW = CInt(w)

If h >= w And iH = h And iW = w Then
    getDimDisplay = CStr(iW) & CStr(iH)
Else
    If h >= w And iH <> h And iW = w Then
        getDimDisplay = CStr(iW) & "x" & CStr(h)
    Else
        If w >= h And iH = h And iW <> w Then
            getDimDisplay = CStr(iH) & "x" & CStr(w)
        Else
            If w >= h And iH <> h And iW <> w Then
                getDimDisplay = CStr(h) & "x" & CStr(w)
            End If
        End If
    End If
End If
End Function

answered Jan 24, 2014 at 10:12

PPh's user avatar

4

Fixed the error I was seeing with some numbers not being handled correctly. I was missing a comparison scenario — should have been four comparisons to make instead of three for each h>=w or w>=h situation. Yay! Thanks folks! Here’s the working code:

Function getDimDisplay(h As Single, w As Single) As String

Dim iH%:    iH = CInt(h)
Dim iW%:    iW = CInt(w)

If h >= w And iH = h And iW = w Then
    getDimDisplay = CStr(w) & CStr(h)
Else
    If h >= w And iH <> h And iW = w Then
        getDimDisplay = CStr(w) & "x" & CStr(iH)
    Else
        If h >= w And iH = h And iW <> w Then
            getDimDisplay = CStr(w) & "x" & CStr(iH)
        Else
            If h >= w And iH <> h And iW <> w Then
                getDimDisplay = CStr(w) & "x" & CStr(h)
            Else
                If w >= h And iH = h And iW = w Then
                    getDimDisplay = CStr(iH) & CStr(iW)
                Else
                    If w >= h And iH <> h And iW = w Then
                        getDimDisplay = CStr(h) & "x" & CStr(iW)
                    Else
                        If w >= h And iH = h And iW <> w Then
                            getDimDisplay = CStr(iH) & "x" & CStr(w)
                        Else
                            If w >= h And iH <> h And iW <> w Then
                                getDimDisplay = CStr(h) & "x" & CStr(w)
                            End If
                        End If
                    End If
                End If
            End If
        End If
    End If
End If    
End Function

Zsmaster's user avatar

Zsmaster

1,5504 gold badges22 silver badges28 bronze badges

answered Jan 28, 2014 at 15:06

user3229658's user avatar

user3229658user3229658

511 gold badge1 silver badge2 bronze badges

In Select case, you can’t use «and» operator, instead you have to use a comma «,»

Select Case h
Case Is >= w , Is = iH
    If w = iW Then
    '   do stuff
    Else
    '   do other stuff
    End If
Case Is <= w , Is = iH
    If w <> iW Then
    '   do stuff
    End If
Case Is > -w , Is <> iH
    If w <> iW Then
    '   do stuff
    End If
End Select

Please see the below example for more clarity

http://gadoth.com/excel-vba-series-post-9-select-case/

0m3r's user avatar

0m3r

12.2k15 gold badges33 silver badges70 bronze badges

answered Jul 31, 2017 at 6:46

Rajathithan Rajasekar's user avatar

2

Like this post? Please share to your friends:
  • Vba excel select all in listbox
  • Vba excel saving a file
  • Vba excel saveas fileformat
  • Vba excel range все ячейки
  • Vba excel range адрес