Оператор 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 выглядит изящней.
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
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!
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:
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:
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
I’m looking to carry out a Select Case with just one case — where the case is not equal to «P», «Ev» or «Af».
This is what I have so far.
Select Case Range("my_range").Offset(0, column_offset).Value
Case Not "P", "Ev", "Af"
'my code
End Select
The case could equal 50 different values and I want the same action (under 'my code
) to be performed for all of them unless the result is P, Ev or Af.
I’ve also tried Not "P", Not "Ev", Not "Af"
along with replacing ,
with Or
but to no avail.
The response each and every time is:
Run-time error ’13’: Type mismatch.
I know I could replace this with an if statement along the lines of…
If Range("my_range").Offset(0, column_offset).Value <> "P" And Range("my_range").Offset(0, column_offset).Value <> "Ev" And Range("my_range").Offset(0, column_offset).Value <> "Af" Then
'my code
End if
but I’d prefer to use the Select Case option if I can.
Any thoughts anyone?
Many thanks
EDIT
I should also say I did try using
Select Case Range("my_range").Offset(0, column_offset).Value
Case "P", "Ev", "Af"
Exit Select
Case Else
'my code
End Select
but the error message:
Compile error: Expected: Do or For or Sub or Function or Property
kept popping up.
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.
Conditional Statements in Excel VBA
Related Link: If…Then…Else Statements (VBA).
There are primarily two Conditional Statements in VBA: If…Then…Else Statements and Select…Case Statement. In both of these, one or more conditions are evaluated and a block of code is executed depending on the result of the evaluation.
Select…Case Statement (VBA)
If…Then…Else Statements (VBA)
————————————————————————————————
Contents:
Select…Case Statement (VBA)
Syntax
Using the To keyword to specify the upper and lower range of values
Using the Is keyword (with a comparison operator) to compare values
Using a comma to separate multiple expressions or ranges in each Case clause
Option Compare Setting
Nesting
GoTo statement
Select…Case compared to If…Then…Else Statements
————————————————————————————————
Select…Case Statement (VBA)
Executes different blocks of code or statements, depending on the respective condition(s) being met. It evaluates an expression and based on its result executes one of the many set of statements. It is very similar to the If…Then…Else statements.
Syntax
Select Case expression
Case expression_value_1
statements_1
Case expression_value_n
statements_n
Case Else
else_statements
End Select
expression can be a variable, a field or a range. It can be expresesed using a vba function -> as «IsNumeric(rng)» or «rng.HasFormula», where ‘rng’ is a Range variable. It should evaluate to a Boolean value, String value, Numeric value or Date type ie. to any of the basic data types of Boolean, Byte, Integer, Long, Single, Double, Decimal, Date, Object, String, Variant, … It is necessary to specify an expression. It is the value of this expression which is tested and compared (with expression_value) in each Case and when it matches, the statements specified in the matching Case are executed.
expression_value [expression_value_1 … expression_value_n] -> the data type of expression_value should match or be convertible to that of expression. In each Case, the value of the expression is compared to the expression_value, and if a match is found, the specified statements get executed. It is necessary to specify atleast one expression_value. Expression_values are tested in the order they are mentioned. These (expression_value) are like a list of conditions and when a condition is met, the relevant block of code gets executed.
statements [statements_1 … statements_n] -> statements specified in a particular Case get executed if the value of the expression matches the relevant expression_value of that Case.
Case Else -> expression_values are tested in the order they are mentioned and if a match is found, its respective statements get executed and no subsequent expression_value is tested thereafter. If no match is found for any expression_value, Case Else clause comes into play and the else_statements get executed. It is Optional to have the Case Else clause.
else_statements -> these statements get executed if no match is found in any of the expression_values. It is optional to specify else_statements. If a match has not been found in any expression_value and else_statements are not specified also, in this case no code will be executed in the Select…Case Statements block.
End Select -> terminates the Select…Case block of statements and it is necessary to mention these keywords at the end.
Example:
Sub selectCase1()
‘making strAge equivalent to «young» will return the message «Less than 40 years»
Dim strAge As String
strAge = «young»
Select Case strAge
Case «senior citizen»
MsgBox «Over 60 years»
Case «middle age»
MsgBox «Between 40 to 59 years»
Case «young»
MsgBox «Less than 40 years»
Case Else
MsgBox «Invalid»
End Select
End Sub
Using the To keyword to specify the upper and lower range of values
Use the To keyword in expression_value to specify the upper and lower range of matching values, as shown below. The value to the left of To keyword should be less than or equal to the value to the right of the To keyword. Range can also be specified for character strings.
Example:
Sub selectCaseTo()
‘entering marks as 69 will return the message «Average»; entering marks as 101 will return the message «Out of Range»
Dim iMarks As Integer
iMarks = InputBox(«Enter marks»)
Select Case iMarks
Case 70 To 100
MsgBox «Good»
Case 40 To 69
MsgBox «Average»
Case 0 To 39
MsgBox «Failed»
Case Else
MsgBox «Out of Range»
End Select
End Sub
Using the Is keyword (with a comparison operator) to compare values
To include a comparison operator (=, <>, <, >, <=, or >=) in expression_value, use the Is keyword. The Is keyword is automatically inserted before a comparison operator, if not specifically included. See below example.
Example:
Sub selectCaseIs()
‘if sngTemp equals 39.5, returned message is «Moderately Hot»
Dim sngTemp As Single
sngTemp = 39.5
Select Case sngTemp
Case Is >= 40
MsgBox «Extremely Hot»
Case Is >= 25
MsgBox «Moderately Hot»
Case Is >= 0
MsgBox «Cool Weather»
Case Is < 0
MsgBox «Extremely Cold»
End Select
End Sub
Using a comma to separate multiple expressions or ranges in each Case clause
Multiple expressions or ranges can be specified in each Case clause, by separating each expression with a comma (which has the effect of the OR operator). Multiple expressions or ranges can also be specified for character strings. See below examples.
Example:
Sub selectCaseMultiple_1()
‘if alpha equates to «Hello», the returned message is «Odd Number or Hello»
Dim alpha As Variant
alpha = «Hello»
Select Case alpha
Case a, e, i, o, u
MsgBox «Vowels»
Case 2, 4, 6, 8
MsgBox «Even Number»
Case 1, 3, 5, 7, 9, «Hello»
MsgBox «Odd Number or Hello»
Case Else
MsgBox «Out of Range»
End Select
End Sub
Example:
In this example, the string comparison «apples» To «grapes» determines a value between «apples» and «grapes» in alphabetical order, and uses the default text comparison method of Binary (which is case-sensitive) because Option Compare Statement is not specified — see below.
Sub SelectCaseMultiple_OptionCompare_NotSpecified()
‘Option Compare is NOT specified and therefore text comparison will be case-sensitive
‘bananas will return the message «Text between apples and grapes, or specifically mangoes, or the numbers 98 or 99»; oranges will return the message «Out of Range»; Apples will return the message «Out of Range».
Dim var As Variant, strResult As String
var = InputBox(«Enter»)
Select Case var
Case 1 To 10, 11 To 20: strResult = «Number is between 1 and 20»
Case «apples» To «grapes», «mangoes», 98, 99: strResult = «Text between apples and grapes, or specifically mangoes, or the numbers 98 or 99»
Case Else: strResult = «Out of Range»
End Select
MsgBox strResult
End Sub
Option Compare Setting:
You can compare string data using string comparison methods of Binary, Text or Database. Database is used only with Microsoft Access.
Option Compare Binary makes string comparisons based on a binary sort order (in Microsoft Windows, the code page determines the sort order — wherein ANSI 1252 is used for English and many European languages) -> A < B < U < Z < a < b < u < z < À < Û < à < û
Option Compare Text makes string comparisons which are not based on a case-sensitive text sort order -> (A=a) < (À = à) < (B=b) < (U=u) < (Û = û) < (Z=z)
Option Compare Statement (viz. Option Compare Binary or Option Compare Text) can be used to set the comparison method. It must be used at the module level, before any procedure. If the Option Compare Statement is not specified, the default text comparison method is Binary.
Example — Option Compare Binary or Default
Option Compare Binary
————————————————————————
Sub OptionCompareBinary_Specified()
‘Option Compare Binary is specified and therefore text comparison will be case-sensitive
‘»Apples» will return the message «Out of Range»; «Grapes» will return «Out of Range» («G» comes before «a» in ANSI code); «gRound» will return «Text between apples and grapes», whereas «ground» is «Out of Range»
Dim str As String
str = InputBox(«Enter text»)
Select Case str
Case «apples» To «grapes»
MsgBox «Text between apples and grapes»
Case Else
MsgBox «Out of Range»
End Select
End Sub
Example — Option Compare Text
Option Compare Text
———————————————————————-
Sub OptionCompareText_Specified()
‘Option Compare Text is specified and therefore text comparison will NOT be case-sensitive;
‘Both «Apples» and «Grapes» will return the message «Text between apples and grapes»; both «gRound» and «ground» will return «Out of Range»
Dim str As String
str = InputBox(«Enter text»)
Select Case str
Case «apples» To «grapes»
MsgBox «Text between apples and grapes»
Case Else
MsgBox «Out of Range»
End Select
End Sub
Nesting:
Select…Case block of statements can be nested within each other and also with If…Then…Else statements and VBA loops (as inner or outer loop), without any limit. When Select…Case is nested within the other, it must be a complete block and terminate with its own End Select, within a specific Case or Case Else clause of the outer Select…Case block.
Example: (using nested Select…Case statements)
Sub selectCaseNested1()
‘check if a range is empty; and if not empty, whether has a numeric value and if numeric then if also has a formula; and if not numeric then what is the text length.
Dim rng As Range, iLength As Integer
Set rng = ActiveSheet.Range(«A1»)
Select Case IsEmpty(rng)
Case True
MsgBox rng.Address & » is empty»
Case Else
Select Case IsNumeric(rng)
Case True
MsgBox rng.Address & » has a numeric value»
Select Case rng.HasFormula
Case True
MsgBox rng.Address & » also has a formula»
End Select
Case Else
iLength = Len(rng)
MsgBox rng.Address & » has a Text length of » & iLength
End Select
End Select
End Sub
Example: (Text Manipulation with nested Conditional Statements and VBA Loops)
Function StringManipulation(str As String) As String
‘This code customizes a string text as follows:
‘1. removes numericals from a text string;
‘2. removes leading, trailing & inbetween spaces (leaves single space between words);
‘3. adds space (if not present) after each exclamation, comma, full stop and question mark;
‘4. capitalizes the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark;
Dim iTxtLen As Integer, iStrLen As Integer, n As Integer, i As Integer, ansiCode As Integer
‘—————————
‘REMOVE NUMERICALS
‘chr(48) to chr(57) represent numericals 0 to 9 in ANSI/ASCII character codes
For i = 48 To 57
‘remove all numericals from the text string using vba Replace function:
str = Replace(str, Chr(i), «»)
Next i
‘—————————
‘REMOVE LEADING, TRAILING & INBETWEEN SPACES (LEAVE SINGLE SPACE BETWEEN WORDS)
‘use the worksheet TRIM function. Note: the TRIM function removes space character with ANSI code 32, does not remove the nonbreaking space character with ANSI code 160
str = Application.Trim(str)
‘—————————
‘ADD SPACE (IF NOT PRESENT) AFTER EACH EXCLAMATION, COMMA, DOT AND QUESTION MARK:
‘set variable value to string length:
iTxtLen = Len(str)
For n = iTxtLen To 1 Step -1
‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns full stop; Chr(63) returns question mark;
If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then
‘check if space is not present:
If Mid(str, n + 1, 1) <> Chr(32) Then
‘using Mid & Right functions to add space — note that current string length is used:
str = Mid(str, 1, n) & Chr(32) & Right(str, iTxtLen — n)
‘update string length — increments by 1 after adding a space (character):
iTxtLen = iTxtLen + 1
End If
End If
Next n
‘—————————
‘DELETE SPACE (IF PRESENT) BEFORE EACH EXCLAMATION, COMMA, DOT & QUESTION MARK:
‘reset variable value to string length:
iTxtLen = Len(str)
For n = iTxtLen To 1 Step -1
‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns full stop; Chr(63) returns question mark;
If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then
‘check if space is present:
If Mid(str, n — 1, 1) = Chr(32) Then
‘using the worksheet Replace function to delete a space:
str = Application.Replace(str, n — 1, 1, «»)
‘omit rechecking the same character again — position of n shifts (decreases by 1) due to deleting a space character:
n = n — 1
End If
End If
Next n
‘—————————
‘CAPITALIZE LETTERS:
‘capitalize the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark, while all other letters are lower case
iStrLen = Len(str)
For i = 1 To iStrLen
‘determine the ANSI code of each character in the string
ansiCode = Asc(Mid(str, i, 1))
Select Case ansiCode
’97 to 122 are the ANSI codes equating to small cap letters «a» to «z»
Case 97 To 122
If i > 2 Then
‘capitalizes a letter whose position is 2 characters after (1 character after, will be the space character added earlier) an exclamation, full stop and question mark:
If Mid(str, i — 2, 1) = Chr(33) Or Mid(str, i — 2, 1) = Chr(46) Or Mid(str, i — 2, 1) = Chr(63) Then
Mid(str, i, 1) = UCase(Mid(str, i, 1))
End If
‘capitalize first letter of the string:
ElseIf i = 1 Then
Mid(str, i, 1) = UCase(Mid(str, i, 1))
End If
‘if capital letter, skip to next character (ie. next i):
Case Else
GoTo skip
End Select
skip:
Next i
‘—————————
‘manipulated string:
StringManipulation = str
End Function
Sub Str_Man()
‘specify text string to manipulate & get manipulated string
Dim strText As String
‘specify the text string, which is required to be manipulated
strText = ActiveSheet.Range(«A1»).Value
‘the manipulated text string is entered in range A5 of the active sheet, on running the procedure:
ActiveSheet.Range(«A5»).Value = StringManipulation(strText)
End Sub
GoTo statement
Use the GoTo statement to jump to a line within the procedure. The GoTo statement consists of 2 parts: (1) The GoTo statement which is the GoTo keywords followed by a Label which is the identifier; and (2) The Label — this consists of the Name of the Label followed by a colon, and then has a line of code. On satisfying a condition, the GoTo statement transfers control to a separate line of code within the procedure, identified by the Label. GoTo statement is usually avoidable if there is an alternate solution (usually there is — many times you can use If…Then…Else and Select…Case statements alternatively). It makes the code somewhat unreadable and confusing. It is used best for error handling, viz. «On Error GoTo».
For live codes of running Select…Case Statements, click to download excel file.
Select…Case compared to If…Then…Else Statements
Both are Conditional Statements, wherein one or more conditions are evaluated and a block of code is executed depending on the result of the evaluation.
The difference lies in that in a Select…Case statement, a single expression (or variable) is considered and evaluated at a time. The variable to be evaluated is determined in the first line of «Select Case expression», and then multiple Case statements specify the possible values. Whereas in If…Then…Else statements, multiple expressions (or variables) can be considered and evaluated simultaneously. Select…Case statement tests a single item for several possible values, whereas If…Then…Else statements test multiple items for several possible values. In this sense, If…Then…Else statements are more flexible in testing multiple variables for multiple conditions.
In case of a large number of conditions, If…Then…Else statements might get and appear confusing and the code tends to become unreadable.
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
- Binary means that VBA checks the case of the letters – case sensitive.
- 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.)
Today’s focus is on the VBA Select Case statement, which is often comfortable to use when you need to execute different code depending on the value of a certain expression. Usually you won’t be using Select Case when you need to differentiate between less than 3 specific values of an expression. In this post I will want to cover both the How of using Select Case as well as the When and Why.
Let’s start with the definition and a few simple examples of how to use the VBA Select Case statement.
Select Case definition
Below is the definition of the Select Case statement:
Select Case testexpression [ Case expressionlist [ statements ] ] ... [ Case Else [ elsestatements ] ] End Select
The Select Case block basically contains a list of Cases (“expressionlist” expressions) followed by a list of statements to be executed whenever a specific “expressionlist” is evaluated to be true or matches the “testexpression”. Only the statements for the first matched Case are executed. The remaining ones will be omitted. Notice also the Case Else statement. Case Else defines a list of “elsestatements” to be executed if none of the remaining Cases are matched/evaluated true. It is a failover Case scenario if you will or simply a Case covering the whole remaining spectrum of Cases. Enough of this – time for some examples.
Select Case examples
Dim direction as String '... Select Case direction Case "Forward" Debug.Print "Move forward!" Case "Backward" Debug.Print "Move back!" Case "Left" Debug.Print "Turn left!" Case "Right" Debug.Print "Turn right!" End Select
The above is a good example of how to apply the Select Case statement. Select Case is usually used when we have a discreet spectrum of values for which there are separate statements we wish to execute for each. Select Case works also for numbers:
On Error Resume Next '... Select Case Err.Number Case 11: Debug.Print "Divide by zero!" Err.Clear Case 6: Debug.Print "Overflow!" Err.Clear Case Else: Debug.Print "Other error" Err.Clear End Select
Err for those unacquainted with VBA Error Handling is an object managing raised errors. When an error is raised the Err.Number variable is populated with the VBA number of the encountered error. In case we want to define separate handlers for each error number the VBA Select Case statement will definitely be the appropriate tool.
The VBA Select Case “testexpression” needs to evaluate to one of the supported data types: Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, Short, Single, String
Select Case Is
With Select Case we are used to each Case being specified for a specific single value of our “testexpression”. However, VBA facilitates also the Is statement which can be used in tandem with the Case expression to compare our value using operators such as greater than (>), less than (<), greater or equal to (>=) and so on.
Dim ageUS as Long '...in most states... Select Case ageUS Case Is < 17 Debug.Print "You can't drive or drink alcohol" Case Is < 21 Debug.Print "You can drive, but can't drink alcohol" Case Else Debug.Print "Now you can get drunk or drive. But not at the same time!" End Select
The Is statement again will evaluate from the top and execute only statements for the first true Case expression. Hence, if you are 16 you won’t get the remaining 2 messages.
Select Case with ranges
Similarly Select Case allows you to specify a range of values using the To statement:
Dim ageUS as Long '...in most states... Select Case ageUS Case 0 to 16 Debug.Print "You can't drive or drink alcohol" Case 17 to 20 Debug.Print "You can drive, but can't drink alcohol" Case Else Debug.Print "Now you can get drunk or drive. But not at the same time!" End Select
Select Case with enumeration
In some cases you might want to enumerate specific values that should be handled by common statements. In such cases be sure to separate them using a comma “,”.
Dim name as String '... Select Case name Case "Michael", "Mike", "Mikey" Debug.Print "Michael" Case "Thomas", "Tom", "Tommy" Debug.Print "Thomas" Case "Andrew", "Andy": Debug.Print "Andrew" Case Else Debug.Print "Basic name unknown" End Select
Select Case vs If-Else vs Iif
Now that we know our way around the VBA Select Case statment let’s remind the other condition statements in VBA we have available and when to use each.
When to use Select Case?
As you probably already learned Select Case is to be used only when you need to evaluate a single expression (in Select Case) which will provide a single value. That value can be handled separately for different Cases. Cases can handles single values, enumerations and numerical comparisons (>,<,>=,= etc.), but they can’t evaluate separate expressions! This is when we should you the If-Else conditions or the Iif function.
When to use If-ElseIf-Else
Use If-ElseIf-Else statements when:
- You need to evaluate a single option that does not simply return a value
- Each option needs to be evaluated as a separate expression
Don’t use If-ElseIf-Else when:
- You need to define a single variable based on a certain condition (use Iif for that – next section)
- You need to evaluate a single expression and execute different blocks of code depending on the result (use Select Case for that)
When to use the Iif function?
If you haven’t heard of the Iif function do read this post. As it is a great simple function that can’t help shorten your VBA code and make it more clear. Use the Iif function when you need to evaluate a single boolean expression to return either of 2 values. Simple example below:
Dim i as Integer, str as String '... str = Iif(i = 10, "=10", "<>10")