No, you didn’t:
If Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
An alternative would be to use a Select Case
statement. These are especially useful if you have many conditions to test:
Select Case Cells(i, 3).Value
Case "BRITISH TELECOM", _
"CHRISTIES INTERNATIO", _
"DTAG", _
"IMAGINE COMMUNICATIONS CORP"
'Do something
Case "Some other string", _
"and another string"
'Do something else
Case Else
'Do something if none of the other statements evaluated to True
End Select
That Select Case
statement would be equivalent to the following If
statement:
If Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
'Do something
ElseIf Cells(i, 3).Value = "Some other string" Or _
Cells(i, 3).Value = "and another string" Then
'Do something else
Else
'Do something if none of the other statements evaluated to True
End If
Unrelated to the actual question, but in response to a further question in comments:
If you have error values in your data, they will not be able to be compared to Strings, so you will need to test for errors first.
For example:
If IsError(Cells(i, 3).Value) Then
'Do whatever you want to do with error values such as #N/A
ElseIf Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
'...
or
If IsError(Cells(i, 3).Value) Then
'Do whatever you want to do with error values such as #N/A
Else
Select Case Cells(i, 3).Value
Case "BRITISH TELECOM", _
"CHRISTIES INTERNATIO", _
"DTAG", _
"IMAGINE COMMUNICATIONS CORP"
'Do something
Case "Some other string", _
"and another string"
'Do something else
Case Else
'Do something if none of the other statements evaluated to True
End Select
End If
When build expressions for If Statements, you can also use any function that generates TRUE or False. VBA has a few of these functions:
Function | Description |
---|---|
IsDate | Returns TRUE if expression is a valid date |
IsEmpty | Check for blank cells or undefined variables |
IsError | Check for error values |
IsNull | Check for NULL Value |
IsNumeric | Check for numeric value |
They can be called like this:
Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:
You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:
Comparing Text
You can also compare text similar to comparing numbers:
When comparing text, you must be mindful of the “Case” (upper or lower). By default, VBA considers letters with different cases as non-matching. In other words, “A” <> “a”.
If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:
After making that declaration “A” = “a”:
VBA If Like
The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:
Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters. So the above If statement will return TRUE. The Like operator is an extremely powerful, but often under-used tool for dealing with text.
If Loops
VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.
Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:
If Else Examples
Now we will go over some more specific examples.
Check if Cell is Empty
This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:
Check if Cell Contains Specific Text
The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:
Check if cell contains text
This code will test if a cell is text:
If Goto
You can use the result of an If statement to “Go to” another section of code.
Delete Row if Cell is Blank
If MessageBox Yes / No
With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No. You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.
Here is the Yes/No Message Box in practice:
VBA If, ElseIf, Else in Access VBA
The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.
You can use an If statement to check if there are records in a Recordset.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Logical Operators: AND, OR, NOT, IF NOT in Excel VBA
Updated January 20, 2023
Excel VBA Logical Operators
Let’s say you want to process a customer order. For that, you want to first check to see if the ordered product exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in handy in such cases. Logical operators are used to evaluate more than one condition.
The main Excel VBA logical operators AND, OR, NOT are listed in the table below:
S/N | Operator | Description | Example | Output |
---|---|---|---|---|
1 | AND | AND: This is used to combine more than one condition. If all the conditions are true, AND evaluates to true. If any of the condition is false, AND evaluates to false | If true = true AND false = true THEN | false |
2 | OR | OR: This is used to combine more than one condition. If any of the conditions evaluate to true, OR returns true. If all of them are false, OR returns false | If true = true OR true = false THEN | true |
3 | NOT | NOT: This one works like an inverse function. If the condition is true, it returns false, and if a condition is false, it returns true. | If NOT (true) Then | false |
VBA Logical Operators Example Source Code
For the sake of simplicity, we will be comparing hard coded numbers.
Add ActiveX buttons to the sheet from the “Insert option.”
Set the properties as shown in the image below
VBA Logical Operators
The following table shows the properties that you need to change and the values that you need to update too.
Источник
VBA IF OR
IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.
IF OR Function in VBA
Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.
Table of contents
You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)
How to Use IF with OR Function in VBA?
We will show you a simple example of using the IF OR function in VBA.
A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.
Now, look at the syntax of the IF OR function in VBA.
It is the same as we saw in the worksheet example. For a better understanding, look at the below example.
We have the previous month’s price, the last 6-month average price, and the current monthly price here.
To decide whether to buy the product, we need to do some tests here, and those tests are.
If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”
Step 1: Open the IF condition inside the Sub procedure.
Code:
Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value
Step 3: The first logical condition completes. Now, open OR statement.
Code:
Step 4: Now, apply the second logical condition as Range(“D2”).Value
Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”
Code:
Step 6: In the next line, write what the result should be if the logical test Logical Test A logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test. read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.
Code:
Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.
Code:
Step 8: Close the IF statement with “End If.”
Code:
We complete the coding part.
Let us run this code using F5 or manually through the run option and see the result in cell E2.
We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.
IF OR VBA Function with Loops (Advanced)
Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loops Use VBA Loops A VBA loop in excel is an instruction to run a code or repeat an action multiple times. read more .
We have added a few more lines for the above data set.
We need to use the For Next Loop here.
Just keep the current code as it is.
Declare the variable as an Integer.
Now, open For Next Loop from 2 to 9.
For example, Range (“D2”).Value should be Range (“D” & k).Value
Now, run the code. First, we should get the status in all the cells.
You can copy the code below.
Code:
Recommended Articles
This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –
Источник
Adblock
detector
This post provides a complete guide to the VBA If Statement in VBA. If you are looking for the syntax then check out the quick guide in the first section which includes some examples.
The table of contents below provides an overview of what is included in the post. You use this to navigate to the section you want or you can read the post from start to finish.
“Guess, if you can, and choose, if you dare.” – Pierre Corneille
Quick Guide to the VBA If Statement
Description | Format | Example |
---|---|---|
If Then | If [condition is true] Then [do something] End If |
If score = 100 Then Debug.Print «Perfect» End If |
If Else | If [condition is true] Then [do something] Else [do something] End If |
If score = 100 Then Debug.Print «Perfect» Else Debug.Print «Try again» End If |
If ElseIf | If [condition 1 is true] Then [do something] ElseIf [condition 2 is true] Then [do something] End If |
If score = 100 Then Debug.Print «Perfect» ElseIf score > 50 Then Debug.Print «Passed» ElseIf score <= 50 Then Debug.Print «Try again» End If |
Else and ElseIf (Else must come after ElseIf’s) |
If [condition 1 is true] Then [do something] ElseIf [condition 2 is true] Then [do something] Else [do something] End If |
If score = 100 Then Debug.Print «Perfect» ElseIf score > 50 Then Debug.Print «Passed» ElseIf score > 30 Then Debug.Print «Try again» Else Debug.Print «Yikes» End If |
If without Endif (One line only) |
If [condition is true] Then [do something] | If value <= 0 Then value = 0 |
The following code shows a simple example of using the VBA If statement
If Sheet1.Range("A1").Value > 5 Then Debug.Print "Value is greater than five." ElseIf Sheet1.Range("A1").Value < 5 Then Debug.Print "value is less than five." Else Debug.Print "value is equal to five." End If
The Webinar
Members of the Webinar Archives can access the webinar for this article by clicking on the image below.
(Note: Website members have access to the full webinar archive.)
What is the VBA If Statement
The VBA If statement is used to allow your code to make choices when it is running.
You will often want to make choices based on the data your macros reads.
For example, you may want to read only the students who have marks greater than 70. As you read through each student you would use the If Statement to check the marks of each student.
The important word in the last sentence is check. The If statement is used to check a value and then to perform a task based on the results of that check.
The Test Data and Source Code
We’re going to use the following test data for the code examples in this post:
You can download the test data with all the source code for post plus the solution to the exercise at the end:
Format of the VBA If-Then Statement
The format of the If Then statement is as follows
If [condition is true] Then
The If keyword is followed by a Condition and the keyword Then
Every time you use an If Then statement you must use a matching End If statement.
When the condition evaluates to true, all the lines between If Then and End If are processed.
If [condition is true] Then [lines of code] [lines of code] [lines of code] End If
To make your code more readable it is good practice to indent the lines between the If Then and End If statements.
Indenting Between If and End If
Indenting simply means to move a line of code one tab to the right. The rule of thumb is to indent between start and end statements like
Sub … End Sub
If Then … End If
If Then… ElseIf … Else … Endif
For … Next
Do While … Loop
Select Case … End Case
To indent the code you can highlight the lines to indent and press the Tab key. Pressing Shift + Tab will Outdent the code i.e. move it one tab to the left.
You can also use the icons from the Visual Basic Toolbar to indent/outdent the code
Select code and click icons to indent/outdent
If you look at any code examples on this website you will see that the code is indented.
A Simple If Then Example
The following code prints out the names of all students with marks greater than 50 in French.
' https://excelmacromastery.com/ Sub ReadMarks() Dim i As Long ' Go through the marks columns For i = 2 To 11 ' Check if marks greater than 50 If Sheet1.Range("C" & i).Value > 50 Then ' Print student name to the Immediate Window(Ctrl + G) Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value End If Next End Sub
Results
Bryan Snyder
Juanita Moody
Douglas Blair
Leah Frank
Monica Banks
Play around with this example and check the value or the > sign and see how the results change.
Using Conditions with the VBA If Statement
The piece of code between the If and the Then keywords is called the condition. A condition is a statement that evaluates to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like >,<,<>,>=,<=,=.
The following are examples of conditions
Condition | This is true when |
---|---|
x < 5 | x is less than 5 |
x <= 5 | x is less than or equal to 5 |
x > 5 | x is greater than 5 |
x >= 5 | x is greater than or equal to 5 |
x = 5 | x is equal to 5 |
x <> 5 | x does not equal 5 |
x > 5 And x < 10 | x is greater than 5 AND x is less than 10 |
x = 2 Or x >10 | x is equal to 2 OR x is greater than 10 |
Range(«A1») = «John» | Cell A1 contains text «John» |
Range(«A1») <> «John» | Cell A1 does not contain text «John» |
You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.
When equals is used in a condition it means “is the left side equal to the right side”.
The following table demonstrates how the equals sign is used in conditions and assignments
Using Equals | Statement Type | Meaning |
---|---|---|
Loop Until x = 5 | Condition | Is x equal to 5 |
Do While x = 5 | Condition | Is x equal to 5 |
If x = 5 Then | Condition | Is x equal to 5 |
For x = 1 To 5 | Assignment | Set the value of x to 1, then to 2 etc. |
x = 5 | Assignment | Set the value of x to 5 |
b = 6 = 5 | Assignment and Condition | Assign b to the result of condition 6 = 5 |
x = MyFunc(5,6) | Assignment | Assign x to the value returned from the function |
The last entry in the above table shows a statement with two equals. The first equals sign is the assignment and any following equals signs are conditions.
This might seem confusing at first but think of it like this. Any statement that starts with a variable and an equals is in the following format
[variable] [=] [evaluate this part]
So whatever is on the right of the equals sign is evaluated and the result is placed in the variable. Taking the last three assignments again, you could look at them like this
[x] [=] [5]
[b] [=] [6 = 5]
[x] [=] [MyFunc(5,6)]
Using ElseIf with the VBA If Statement
The ElseIf statement allows you to choose from more than one option. In the following example we print for marks that are in the Distinction or High Distinction range.
' https://excelmacromastery.com/ Sub UseElseIf() If Marks >= 85 Then Debug.Print "High Destinction" ElseIf Marks >= 75 Then Debug.Print "Destinction" End If End Sub
The important thing to understand is that order is important. The If condition is checked first.
If it is true then “High Distinction” is printed and the If statement ends.
If it is false then the code moves to the next ElseIf and checks it condition.
Let’s swap around the If and ElseIf from the last example. The code now look like this
' https://excelmacromastery.com/ Sub UseElseIfWrong() ' This code is incorrect as the ElseIf will never be true If Marks >= 75 Then Debug.Print "Destinction" ElseIf Marks >= 85 Then ' code will never reach here Debug.Print "High Destinction" End If End Sub
In this case we check for a value being over 75 first. We will never print “High Distinction” because if a value is over 85 is will trigger the first if statement.
To avoid these kind of problems we should use two conditions. These help state exactly what you are looking for a remove any confusion. The example below shows how to use these. We will look at more multiple conditions in the section below.
If marks >= 75 And marks < 85 Then Debug.Print "Destinction" ElseIf marks >= 85 And marks <= 100 Then Debug.Print "High Destinction" End If
Let’s expand the original code. You can use as many ElseIf statements as you like. We will add some more to take into account all our mark classifications.
If you want to try out these examples you can download the code from the top of this post.
Using Else With the VBA If Statement
The VBA Else statement is used as a catch all. It basically means “if no conditions were true” or “everything else”. In the previous code example, we didn’t include a print statement for a fail mark. We can add this using Else.
' https://excelmacromastery.com/ Sub UseElse() If Marks >= 85 Then Debug.Print "High Destinction" ElseIf Marks >= 75 Then Debug.Print "Destinction" ElseIf Marks >= 55 Then Debug.Print "Credit" ElseIf Marks >= 40 Then Debug.Print "Pass" Else ' For all other marks Debug.Print "Fail" End If End Sub
So if it is not one of the other types then it is a fail.
Let’s write some code to go through our sample data and print the student and their classification:
' https://excelmacromastery.com/ Sub AddClass() ' get the last row Dim startRow As Long, lastRow As Long startRow = 2 lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row Dim i As Long, Marks As Long Dim sClass As String ' Go through the marks columns For i = startRow To lastRow Marks = Sheet1.Range("C" & i).Value ' Check marks and classify accordingly If Marks >= 85 Then sClass = "High Destinction" ElseIf Marks >= 75 Then sClass = "Destinction" ElseIf Marks >= 55 Then sClass = "Credit" ElseIf Marks >= 40 Then sClass = "Pass" Else ' For all other marks sClass = "Fail" End If ' Write out the class to column E Sheet1.Range("E" & i).Value = sClass Next End Sub
The results look like this with column E containing the classification of the marks
Results
Remember that you can try these examples for yourself with the code download from the top of this post.
Using Logical Operators with the VBA If Statement
You can have more than one condition in an If Statement. The VBA keywords And and Or allow use of multiple conditions.
These words work in a similar way to how you would use them in English.
Let’s look at our sample data again. We now want to print all the students that got over between 50 and 80 marks.
We use And to add an extra condition. The code is saying: if the mark is greater than or equal 50 and less than 75 then print the student name.
' https://excelmacromastery.com/ Sub CheckMarkRange() Dim i As Long, marks As Long For i = 2 To 11 ' Store marks for current student marks = Sheet1.Range("C" & i).Value ' Check if marks greater than 50 and less than 75 If marks >= 50 And marks < 80 Then ' Print first and last name to Immediate window(Ctrl G) Debug.Print Sheet1.Range("A" & i).Value & Sheet1.Range("B" & i).Value End If Next End Sub
Results
Douglas Blair
Leah Frank
Monica Banks
In our next example we want the students who did History or French. So in this case we are saying if the student did History OR if the student did French:
' Description: Uses OR to check the study took History or French. ' Worksheet: Marks ' Output: Result are printed to the Immediate Windows(Ctrl + G) ' https://excelmacromastery.com/vba-if Sub UseOr() ' Get the data range Dim rg As Range Set rg = shMarks.Range("A1").CurrentRegion Dim i As Long, subject As String ' Read through the data For i = 2 To rg.Rows.Count ' Get the subject subject = rg.Cells(i, 4).Value ' Check if subject greater than 50 and less than 80 If subject = "History" Or subject = "French" Then ' Print first name and subject to Immediate window(Ctrl G) Debug.Print rg.Cells(i, 1).Value & " " & rg.Cells(i, 4).Value End If Next End Sub
Results
Bryan History
Bradford French
Douglas History
Ken French
Leah French
Rosalie History
Jackie History
Using Multiple conditions like this is often a source of errors. The rule of thumb to remember is to keep them as simple as possible.
Using If And
The AND works as follows
Condition 1 | Condition 2 | Result |
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
What you will notice is that AND is only true when all conditions are true
Using If Or
The OR keyword works as follows
Condition 1 | Condition 2 | Result |
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
What you will notice is that OR is only false when all the conditions are false.
Mixing AND and OR together can make the code difficult to read and lead to errors. Using parenthesis can make the conditions clearer.
' https://excelmacromastery.com/ Sub OrWithAnd() Dim subject As String, marks As Long subject = "History" marks = 5 If (subject = "French" Or subject = "History") And marks >= 6 Then Debug.Print "True" Else Debug.Print "False" End If End Sub
Using If Not
There is also a NOT operator. This returns the opposite result of the condition.
Condition | Result |
TRUE | FALSE |
FALSE | TRUE |
The following two lines of code are equivalent.
If marks < 40 Then If Not marks >= 40 Then
as are
If True Then If Not False Then
and
If False Then If Not True Then
Putting the condition in parenthesis makes the code easier to read
If Not (marks >= 40) Then
A common usage of Not when checking if an object has been set. Take a worksheet for example. Here we declare the worksheet
Dim mySheet As Worksheet ' Some code here
We want to check mySheet is valid before we use it. We can check if it is nothing.
If mySheet Is Nothing Then
There is no way to check if it is something as there is many different ways it could be something. Therefore we use Not with Nothing
If Not mySheet Is Nothing Then
If you find this a bit confusing you can use parenthesis like this
If Not (mySheet Is Nothing) Then
The IIF function
Note that you can download the IIF examples below and all source code from the top of this post.
VBA has an fuction similar to the Excel If function. In Excel you will often use the If function as follows:
=IF(F2=””,””,F1/F2)
The format is
=If(condition, action if true, action if false).
VBA has the IIf statement which works the same way. Let’s look at an example. In the following code we use IIf to check the value of the variable val. If the value is greater than 10 we print true otherwise we print false:
' Description: Using the IIF function to check a number. ' Worksheet: Marks ' Output: Result are printed to the Immediate Windows(Ctrl + G) ' https://excelmacromastery.com/vba-if Sub CheckNumberIIF() Dim result As Boolean Dim number As Long ' Prints True number = 11 result = IIf(number > 10, True, False) Debug.Print "Number " & number & " greater than 10 is " & result ' Prints false number = 5 result = IIf(number > 10, True, False) Debug.Print "Number " & number & " greater than 10 is " & result End Sub
In our next example we want to print out Pass or Fail beside each student depending on their marks. In the first piece of code we will use the normal VBA If statement to do this:
' https://excelmacromastery.com/ Sub CheckMarkRange() Dim i As Long, marks As Long For i = 2 To 11 ' Store marks for current student marks = Sheet1.Range("C" & i).Value ' Check if student passes or fails If marks >= 40 Then ' Write out names to to Column F Sheet1.Range("E" & i) = "Pass" Else Sheet1.Range("E" & i) = "Fail" End If Next End Sub
In the next piece of code we will use the IIf function. You can see that the code is much neater here:
' Description: Using the IIF function to check marks. ' Worksheet: Marks ' Output: Result are printed to the Immediate Windows(Ctrl + G) ' https://excelmacromastery.com/vba-if Sub CheckMarkRange() ' Get the data range Dim rg As Range Set rg = shMarks.Range("A1").CurrentRegion Dim i As Long, marks As Long, result As String ' Go through the marks columns For i = 2 To rg.Rows.Count ' Store marks for current student marks = rg.Cells(i, 3).Value ' Check if student passes or fails result = IIf(marks >= 40, "Pass", "Fail") ' Print the name and result Debug.Print rg.Cells(i, 1).Value, result Next End Sub
You can see the IIf function is very useful for simple cases where you are dealing with two possible options.
Using Nested IIf
You can also nest IIf statements like in Excel. This means using the result of one IIf with another. Let’s add another result type to our previous examples. Now we want to print Distinction, Pass or Fail for each student.
Using the normal VBA we would do it like this
' https://excelmacromastery.com/ Sub CheckResultType2() Dim i As Long, marks As Long For i = 2 To 11 ' Store marks for current student marks = Sheet1.Range("C" & i).Value If marks >= 75 Then Sheet1.Range("E" & i).Value = "Distinction" ElseIf marks >= 40 Then ' Write out names to to Column F Sheet1.Range("E" & i).Value = "Pass" Else Sheet1.Range("E" & i).Value = "Fail" End If Next End Sub
Using nested IIfs we could do it like this:
' Description: Using a nested IIF function to check marks. ' Worksheet: Marks ' Output: Result are printed to the Immediate Windows(Ctrl + G) ' https://excelmacromastery.com/vba-if Sub UsingNestedIIF() ' Get the data range Dim rg As Range Set rg = shMarks.Range("A1").CurrentRegion Dim i As Long, marks As Long, result As String ' Go through the marks columns For i = 2 To rg.Rows.Count marks = rg.Cells(i, 3).Value result = IIf(marks >= 55, "Credit", IIf(marks >= 40, "Pass", "Fail")) Debug.Print marks, result Next i End Sub
Using nested IIf is fine in simple cases like this. The code is simple to read and therefore not likely to have errors.
What to Watch Out For
It is important to understand that the IIf function always evaluates both the True and False parts of the statement regardless of the condition.
In the following example we want to divide by marks when it does not equal zero. If it equals zero we want to return zero.
marks = 0 total = IIf(marks = 0, 0, 60 / marks)
However, when marks is zero the code will give a “Divide by zero” error. This is because it evaluates both the True and False statements. The False statement here i.e. (60 / Marks) evaluates to an error because marks is zero.
If we use a normal IF statement it will only run the appropriate line.
marks = 0 If marks = 0 Then 'Only executes this line when marks is zero total = 0 Else 'Only executes this line when marks is Not zero total = 60 / marks End If
What this also means is that if you have Functions for True and False then both will be executed. So IIF will run both Functions even though it only uses one return value. For example
'Both Functions will be executed every time total = IIf(marks = 0, Func1, Func2)
(Thanks to David for pointing out this behaviour in the comments)
If Versus IIf
So which is better?
You can see for this case that IIf is shorter to write and neater. However if the conditions get complicated you are better off using the normal If statement. A disadvantage of IIf is that it is not well known so other users may not understand it as well as code written with a normal if statement.
Also as we discussed in the last section IIF always evaluates the True and False parts so if you are dealing with a lot of data the IF statement would be faster.
My rule of thumb is to use IIf when it will be simple to read and doesn’t require function calls. For more complex cases use the normal If statement.
Using Select Case
The Select Case statement is an alternative way to write an If statment with lots of ElseIf’s. You will find this type of statement in most popular programming languages where it is called the Switch statement. For example Java, C#, C++ and Javascript all have a switch statement.
The format is
Select Case [variable] Case [condition 1] Case [condition 2] Case [condition n] Case Else End Select
Let’s take our AddClass example from above and rewrite it using a Select Case statement.
' https://excelmacromastery.com/ Sub AddClass() ' get the last row Dim startRow As Long, lastRow As Long startRow = 2 lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row Dim i As Long, Marks As Long Dim sClass As String ' Go through the marks columns For i = startRow To lastRow Marks = Sheet1.Range("C" & i).Value ' Check marks and classify accordingly If Marks >= 85 Then sClass = "High Destinction" ElseIf Marks >= 75 Then sClass = "Destinction" ElseIf Marks >= 55 Then sClass = "Credit" ElseIf Marks >= 40 Then sClass = "Pass" Else ' For all other marks sClass = "Fail" End If ' Write out the class to column E Sheet1.Range("E" & i).Value = sClass Next End Sub
The following is the same code using a Select Case statement. The main thing you will notice is that we use “Case 85 to 100” rather than “marks >=85 And marks <=100”.
' https://excelmacromastery.com/ Sub AddClassWithSelect() ' get the first and last row Dim firstRow As Long, lastRow As Long firstRow = 2 lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row Dim i As Long, marks As Long Dim sClass As String ' Go through the marks columns For i = firstRow To lastRow marks = Sheet1.Range("C" & i).Value ' Check marks and classify accordingly Select Case marks Case 85 To 100 sClass = "High Destinction" Case 75 To 84 sClass = "Destinction" Case 55 To 74 sClass = "Credit" Case 40 To 54 sClass = "Pass" Case Else ' For all other marks sClass = "Fail" End Select ' Write out the class to column E Sheet1.Range("E" & i).Value = sClass Next End Sub
Using Case Is
You could rewrite the select statement in the same format as the original ElseIf. You can use Is with Case.
' https://excelmacromastery.com/ Select Case marks Case Is >= 85 sClass = "High Destinction" Case Is >= 75 sClass = "Destinction" Case Is >= 55 sClass = "Credit" Case Is >= 40 sClass = "Pass" Case Else ' For all other marks sClass = "Fail" End Select
You can use Is to check for multiple values. In the following code we are checking if marks equals 5, 7 or 9.
' https://excelmacromastery.com/ Sub TestMultiValues() Dim marks As Long marks = 7 Select Case marks Case Is = 5, 7, 9 Debug.Print True Case Else Debug.Print False End Select End Sub
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.)