Home / VBA / VBA IF And (Test Multiple Conditions)
You can use the AND operator with the VBA IF statement to test multiple conditions, and when you use it allows you to test two conditions simultaneously and get true if both of those conditions are true. And, if any of the conditions is false it returns false in the result.
Combining IF AND
- First, start the IF statement with the “IF” keyword.
- After that, specify the first condition that you want to test.
- Next, use the AND keyword to specify the second condition
- In the end, specify the second condition that you want to test.

To have a better understanding let’s see an example.
Sub myMacro()
If 1 = 1 And 2 > 1 Then
MsgBox "Both of the conditions are true."
Else
MsgBox "Maybe one or both of the conditions are true."
End If
End Sub

If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2 > 1) and here both of the conditions are true, and that’s why it has executes the line of code that we have specified if the result is true.

Now lets if one of these two conditions is false, let me use the different code here.
Sub myMacro1()
If 1 = 1 And 2 < 1 Then
MsgBox "Both of the conditions are true."
Else
MsgBox "Maybe one or both of the conditions are true."
End If
End Sub

In the above code, the second condition is false (2 < 1) and when you run this macro it executes the line of code that we have specified if the result is false.

In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.
Sub myMacro2()
If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then
MsgBox "All the conditions are true."
Else
MsgBox "Some conditions are false."
End If
End Sub

Now we have three conditions to test and we have used the AND after the second condition to specify the third condition. As you learned above that when you use AND, all the conditions need to be true to get true in the result.
When you run this code, it executes the line of code that we have specified for the true.

And if any of the conditions is false, just like you have in the following code, it returns false.
Sub myMacro3()
If 1 = 1 And 2 < 1 And 1 + 1 = 0 Then
MsgBox "All the conditions are true."
Else
MsgBox "Some conditions are false."
End If
End Sub

Excel VBA AND Function
VBA AND function checks the provided statement whether it is true or false. AND function also evaluates the conditions with one another. If both the statements are true, the expression becomes true. Commonly this is associated with different decision-making loops to express the conditions. Comparing to all other logical operators AND returns true only if all the supplied conditions are true.
When you want to evaluate more than one expression and take decisions according to that then logical operators are the best option. AND operators connect two or more conditions together and evaluate the entire statement as a single expression. If all the statement is true, then the total expression returns true. If any expression evaluates false, then the entire statement will return false.
How to Use the AND Function in Excel VBA?
The logical AND can be used along with comparison operators, arithmetic operators, and text, etc. Any number of statements can be connected using AND. The logic behind AND operator is as follows.
| Condition 1 | Condition 2 | Result |
| TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE |
| FALSE | TRUE | FALSE |
| FALSE | FALSE | FALSE |
When more than two conditions are used, each condition should return true to make the entire expression true.
Syntax of VBA AND:
Format of VBA AND is expressed as,
[Condition1] And [Condition 2] And [Condition 3] And………. [Condition n]
- [Condition 1 to Condition n] can be a statement expressed using text and any operators.
You can download this VBA AND Excel Template here – VBA AND Excel Template
Example #1
In this example, you can learn how to use AND function along with comparison operators. You have the marks scored by a student in a different subject. If the total comes more than 80 and 22 marks on the main subject the student got passed in the exam else fail. For this, follow the below steps:
Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.
Step 2: Create a function named result in VBA to do the calculation and find the total mark of all subjects.
Code:
Private Sub result() End Sub
Step 3: Give the marks for different subjects. a, b, c, d are different subjects and the marks scored for each subject is as below. a is the main subject and s is the sum of all subjects a, b, c, d.
Code:
Private Sub result() a = 25 b = 20 c = 20 d = 20 s = a + b + c + d End Sub
Step 4: Now express the conditions as two statements and connect with AND function. IF …Else loop is used to execute the two different results according to the evaluation of the expression.
Code:
Private Sub result() a = 25 b = 20 c = 20 d = 20 s = a + b + c + d If s > 80 And a > 22 Then Else End If End Sub
Step 5: Set the message to show according to the condition valuation. Where both conditions are true the entire expression becomes true and the true section of IF… Else loop will execute. Else the control will move to the false section.
Code:
Private Sub result() a = 25 b = 20 c = 20 d = 20 s = a + b + c + d If s > 80 And a > 22 Then MsgBox "Student got passed the exam" Else MsgBox "Failed" End If End Sub
So if the sum is greater than 80 and the mark for the main subject ‘a’ is greater than 22 then the message “student got passed the exam” will show else fail is the result.
Step 6: Run this code by hitting the F5 or Run button which is placed on the topmost ribbon of VBE. The marks scored in the main subject is greater than 22 and the sum of all subject is greater than 80.
Here both the condition is true so the entire logical AND expression become true and the message in true section of IF… Else loop will be executed.
Example #2
There is no limit for giving the number of conditions with VBA AND. You can use ‘n’ number of conditions and VBA AND operator within a single expression. From an employee database, you have the attendance of a particular employee. You have the number of days that he was present in the office for the past 5 months. If the employee has 25 or more than 25 days’ attendance for every month, he is eligible for a bonus. For this, follow the below steps:
Step 1: In the same module let us start with another subprocedure.
Code:
Private Sub bonus() End Sub
Step 2: To check the above conditions, start with a function ‘bonus’ and attendance for each month.
Private Sub bonus() jan = 25 feb = 24 mar = 25 apr = 25 End Sub
Step 3: Now, check each month’s attendance to confirm whether it is greater than or equal to 25. So multiple ‘AND’ operators are used to check the condition. The value of the entire expression is assigned to ‘b’ which returns a Boolean value.
Code:
Private Sub bonus() jan = 25 feb = 24 mar = 25 apr = 25 b = jan >= 25 And feb >= 25 And mar >= 25 And apr >= 25 End Sub
Step 4: According to this Boolean value, you can a loop. The value of ‘b’ should be true or false.
Code:
Private Sub bonus() jan = 25 feb = 24 mar = 25 apr = 25 b = jan >= 25 And feb >= 25 And mar >= 25 And apr >= 25 If b = "True" Then MsgBox " Employee eligible for bonus" End If If b = "False" Then MsgBox "Employee does not meet the criteria" End If End Sub
Two IF loops are set to execute according to the Boolean value of b. Here apart from Feb all month’s attendance is greater than or equal to 25. But even a single statement evaluates false the entire expression becomes false. ‘AND’ function returns false and the value of ‘b’ becomes false.
Step 5: So the second IF loop will be executed and the message within this will display as “Employee does not meet the criteria.
Here expression is evaluated as follows. First and last two conditions are true and the second condition is false. So while evaluating the entire expression, it becomes false.
Example #3
VBA AND to Evaluate User Credentials. Create a sign-in form using forms and controls in VBA which is available in the code window. For this, follow the below steps:
Step 1: Now Insert a new UserForm inside Visual Basic Editor (VBE). Click on Insert tab > select UserForm. Design a window using Toolbox with a user name, password and a sign-in button.
Step 2: Click the Sign-in button using the AND operator. Once the credentials are provided check the text value comes to both username and password textboxes, Textbox1 and Textbox 2. If the username is “Tutorial” and password is “Edcba1A45” then the credentials are correct and the user will be able to sign in and a welcome message will be displayed. Else error message is displayed.
Code:
Private Sub CommandButton1_Click() If (TextBox1.Text = "Tutorial") And (TextBox2.Text = "Edcba1A45") Then MsgBox "Welcome to your account'" Else MsgBox "Oops username or password is incorrect" End If End Sub
Step 3: Both conditions are expressed in an IF loop. AND operator evaluates these both conditions. Run the form using the run button and give username and password in the text field.
Since the username is “Tutorial” and password is “Edcba1A45” the AND operator returns a true and true block of IF loop will execute.
Things to Remember
- The logical AND function will always return a Boolean value true or false
- Commonly use with decision-making loops.
- Helps to compare ‘n’ number of expressions at a time by connecting with logical AND
- The entire statement returns true only if each statement is true.
Recommended Articles
This is a guide to the VBA AND. Here we discuss how to Use the AND Function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA PasteSpecial
- VBA Dynamic Array
- VBA ReDim Array
- VBA SubString
This Excel tutorial explains how to use the Excel AND function (in VBA) with syntax and examples.
Description
The Microsoft Excel AND function returns TRUE if all conditions are TRUE. It returns FALSE if any of the conditions are FALSE.
The AND function is a built-in function in Excel that is categorized as a Logical Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Please read our AND function (WS) page if you are looking for the worksheet version of the AND function as it has a very different syntax.
Syntax
The syntax for the AND function in Microsoft Excel is:
condition1 And condition2 [... And condition_n]
Parameters or Arguments
- condition1, condition2, … condition_n
- Expressions that you want to test that can either be TRUE or FALSE.
Returns
The AND function returns TRUE if all conditions are TRUE.
The AND function returns FALSE if any of the conditions are FALSE.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
Let’s look at some Excel AND function examples and explore how to use the AND function in Excel VBA code.
This first example combines the AND function with the IF Statement in VBA code:
If LWebsite = "TechOnTheNet.com" And LPages <= 10 Then LBandwidth = "Low" Else LBandwidth = "High" End If
This would set the LBandwidth variable to the string value «Low» if both LWebsite was «TechOnTheNet.com» and LPages <= 10. Otherwise, it would set the LBandwidth variable to the string value «High».
This second example uses the AND function with the OR function in VBA, for example:
If (LWebsite = "TechOnTheNet.com" Or LWebsite = "CheckYourMath.com") And LPages <= 10 Then LBandwidth = "Low" Else LBandwidth = "High" End If
This would set the LBandwidth variable to the string value «Low» if LWebsite was either «TechOnTheNet.com» or «CheckYourMath.com» and LPages <= 10. Otherwise, it would set the LBandwidth variable to the string value «High».
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.)
AND function is a logical function as well as a logical operator. We can have the “TRUE” result if all the conditions are fulfilled in this function. If any of the conditions fails, the output returns “FALSE.” We have a built-in AND command in VBA to use.
We hope you have reviewed our articles on “VBA OROr is a logical function in programming languages, and we have an OR function in VBA. The result given by this function is either true or false. It is used for two or many conditions together and provides true result when either of the conditions is returned true.read more” and “VBA IF ORIF OR is not a single statement; it is a pair of logical functions used together in VBA when we have more than one criteria to check, and when we use the if statement, we receive the true result if either of the criteria is met.read more.” This function is just the opposite of the OR function. In the OR function, to get the result as “TRUE,” we need any of the supplied logical conditions to be satisfied. But in the AND function, it is just the reverse. To get the “TRUE” result, all the supplied logical tests in excelA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more must be satisfied.
Look at the syntax of the AND function in excelThe AND function in Excel is classified as a logical function; it returns TRUE if the specified conditions are met, otherwise it returns FALSE.read more.
Table of contents
- Excel VBA AND Function
- Examples to Use VBA And Function
- Example #1
- Example #2
- Example #3
- Recommended Articles
- Examples to Use VBA And Function
[Logical Test] AND [Logical Test] AND [Logical Test]
In the above, we have two test scores out of 600.
In the result column, we need to get the result as “TRUE” if the score of both the tests is greater than equal to 250.
For example, look at the below image.
When we applied the logical function AND, we got the results. For example, in cells C4 and C5, we got the result as “TRUE” because Test 1 and Test 2 scores are greater than or equal to 250.
Look at the C6 cell here. We have got “FALSE” even though the score of Test 2 equals 250 because, in Test 1, the score is only 179.
Examples to Use VBA And Function
You can download this VBA AND Excel Template here – VBA AND Excel Template
Example #1
For example, we will test the numbers here, whether 25>=20 and 30<=31.
Step 1: Declare the variable as String.
Code:
Sub AND_Example1() Dim K As String End Sub
Step 2: For the variable “k,” we will assign the value by applying the AND function.
Code:
Sub AND_Example1() Dim K As String K = End Sub
Step 3: Supply the first condition as 25>=20.
Code:
Sub AND_Example1() Dim K As String K = 25 >= 20 End Sub
Step 4: Now, open AND function and supply the second logical test, 30<=29.
Code:
Sub AND_Example1() Dim K As String K = 25 >= 20 And 30 <= 29 End Sub
Step 5: Now, show the variable “k” result in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub AND_Example1() Dim K As String K = 25 >= 20 And 30 <= 29 MsgBox K End Sub
Run the macro to see what the result is.
We got the result as “FALSE” because we applied two conditions. The first condition 25>=20, this condition is satisfied, so the result is “TRUE.” However, the second condition, 30<=29, is not satisfied, so the result is “FALSE.” To get the result as TRUE, both the conditions should be satisfied.
Example #2
Now, we will change the logical test to “100>95 AND 100<200.”
Code:
Sub AND_Example2() Dim k As String k = 100 > 95 And 100 < 200 MsgBox k End Sub
Run the code to see the result.
Here, we got “TRUE” as a result because:
1st Logical Test: 100 > 95 = TRUE
2nd Logical Test: 100 < 200 = TRUE
Our final result is “TRUE” since we got the “TRUE” results for both the logical tests.
Example #3
Now, we will see data from the worksheet. First, use the data we have used to show the example of the Excel AND function.
Here the condition is Test 1 Score >= 250 AND Test 2 Score >= 250.
Since we have more than one data cell, we need to use loops to avoid writing unnecessary and time-consuming lines of code. So, we have written the code below for you. The formula and logic are the same because we have only used “VBA For Next LoopAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more.”
Code:
Sub AND_Example3() Dim k As Integer For k = 2 To 6 Cells(k, 3).Value = Cells(k, 1) >= 250 And Cells(k, 2) >= 250 Next k End Sub
It will give the same result as our worksheet function, but we will not get any formulas. We get only results.
Like this, we can apply the AND logical function to test multiple conditions, which should all be “TRUE” to arrive at the desired results.
It works opposite the OR function, where OR requires any supplied conditions to be “TRUE” to arrive at the results. But, AND function requires 100% result in a logical test to arrive at the results.
Recommended Articles
This article is a guide to VBA AND Function. Here, we learn how to use AND logical operator with practical examples and download an Excel template. You may also have a look at other articles related to Excel VBA: –
- Application.Match in VBA
- VBA Wait
- VBA DatePart
- Data Types in VBA
Return to VBA Code Examples
In this Article
- IF…AND
- IF…OR
- IF NOT…
This article will demonstrate how to use the VBA If statement with And, Or and Not.
When we us an IF statement in Excel VBA, the statement will execute a line of code if the condition you are testing is true.
- We can use AND statement and OR statements in conjunction with IF statements to test for more than one condition and direct the code accordingly.
- We can also use a NOT statement with an IF statement to check if the condition is NOT true – it basically is the inverse of the IF statement when used alone.
IF…AND
We can use the IF…AND combination of logical operators when we wish to test for more than one condition where all the conditions need to be true for the next line of code to execute.
For example, consider the following sheet:
To check if the Profit is over $5,000, we can run the following macro:
Sub CheckProfit()
If Range("C5") >= 10000 And Range("C6") < 5000 Then
MsgBox "$5,000 profit achieved!"
Else
Msgbox "Profit not achieved!"
End If
End Sub
This macro will check that the cell C5 is greater or equal to $10,000 AND check that the cell B6 is less than $5,000. If these conditions are BOTH true, it will show the message box.
If we amend the macro to check if C5 is just greater than $10,000, then the profit would not be achieved!
IF…OR
We can use the IF…OR combination of logical operators when we wish to test for more than one condition where only one of the conditions needs to be true for the next line of code to execute.
The format for this is almost identical to the IF…AND example above.
Sub CheckProfit()
If Range("C5") > 10000 Or Range("C6") < 5000 Then
MsgBox "$5,000 profit achieved!"
Else
Msgbox "Profit not achieved!"
End If
End Sub
However, with this macro, because we are using an IF …OR statement, only one of the conditions needs to be true.
IF NOT…
IF..NOT changes the IF statement around – it will check to see if the condition is NOT true rather than checking to see if the condition is true.
Sub CheckProfit()
If NOT Range("C5")< 10000 Or Range("C6") < 5000 Then
MsgBox "$5,000 profit achieved!"
Else
Msgbox "Profit not achieved!"
End If
End Sub
In this example above, the IF statement is checking to see if the value in C5 is NOT smaller than 10000.
Therefore this line of code:
IF Range("C5") > 10000
and this this line of code:
IF NOT Range("C5") < 10000
are testing for the same thing!
VBA Logical Operators: AND, OR, NOT
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
The following table shows the properties that you need to change and the values that you need to update too.
| S/N | Control | Property | Value |
|---|---|---|---|
| 1 | CommandButton1 | Name | btnAND |
| Caption | AND Operator (0 = 0) | ||
| 2 | CommandButton2 | Name | btnOR |
| Caption | OR Operator (1 = 1) Or (5 = 0) | ||
| 3 | CommandButton3 | Name | btnNOT |
| Caption | NOT Operator Not (0 = ) |
Add the following code to btnAND_Click
Private Sub btnAND_Click()
If (1 = 1) And (0 = 0) Then
MsgBox "AND evaluated to TRUE", vbOKOnly, "AND operator"
Else
MsgBox "AND evaluated to FALSE", vbOKOnly, "AND operator"
End If
End Sub
VBA If AND Operator
- “If (1 = 1) And (0 = 0) Then” the if statement uses the AND logical operator to combine two conditions (1 = 1) And (0 = 0). If both conditions are true, the code above ‘Else’ keyword is executed. If both conditions are not true, the code below ‘Else’ keyword is executed.
Add the following code to btnOR_Click
Private Sub btnOR_Click()
If (1 = 1) Or (5 = 0) Then
MsgBox "OR evaluated to TRUE", vbOKOnly, "OR operator"
Else
MsgBox "OR evaluated to FALSE", vbOKOnly, "OR operator"
End If
End Sub
VBA If OR Operator
- “If (1 = 1) Or (5 = 0) Then” the if statement uses the OR logical operator to combine two conditions (1 = 1) And (5 = 0). If any of the conditions is true, the code above Else keyword is executed. If both conditions are false, the code below Else keyword is executed.
Add the following code to btnNOT_Click
Private Sub btnNOT_Click()
If Not (0 = 0) Then
MsgBox "NOT evaluated to TRUE", vbOKOnly, "NOT operator"
Else
MsgBox "NOT evaluated to FALSE", vbOKOnly, "NOT operator"
End If
End Sub
VBA If NOT Operator
- “If Not (0 = 0) Then” the VBA If Not function uses the NOT logical operator to negate the result of the if statement condition. If the conditions is true, the code below ‘Else’ keyword is executed. If the condition is true, the code above Else keyword is executed.
Download Excel containing above code
Brief syntax lesson
Cells(Row, Column) identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: «A», «IV», «XFD») or a number (for example: 1, 256, 16384)
.Cells(Row, Column) identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column) is within the active worksheet. So wsh = ActiveWorkbook wsh.Range is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column) identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value is good.
Cells(Row,Column) like "*Miami*" will give True if the cell is «Miami», «South Miami», «Miami, North» or anything similar.
Cells(Row,Column).Value = "Miami" will give True if the cell is exactly equal to «Miami». «MIAMI» for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami" when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, «South Miami» and «Miami, North».
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, «Miami» and «Florida».
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don’t care about case.
VBA AND function in Excel is categorized as a logical function in VBA. It is a built-in function in MS Office Excel VBA. This function returns true, if all the conditions are TRUE. This function is used to combine more than one condition with using ‘AND’ keyword. This is one of the most used logical operator. It has minimum two conditional input parameters. It returns a Boolean value either True or False.
We can use this function as a worksheet function and also use in VBA. This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA AND function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the AND function, where we can use this VBA AND function and real-time examples.
Table of Contents:
- Overview
- Syntax of VBA AND Function
- Parameters or Arguments
- Where we can apply or use VBA AND Function?
- Example 1: Check two conditions are true or not(TRUE)
- Example 2: Check two conditions are true or not(FALSE)
- Example 3: Check two conditions are true or not(TRUE)
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the VBA AND function is
Condition1 AND Condition2 'or Condition1 AND Condition2 [...AND ConditionN]
The VBA AND function returns Boolean value either True or False. It returns TRUE, if all conditions are TRUE. Otherwise returns FALSE.
Parameters or Arguments
The AND function has one input parameter or argument.
Where
Condition1 & Condition2: Both are required parameters. Here we evaluate specified all conditions are true or not.
Where we can apply or use VBA AND Function?
We can use this VBA AND function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Check two conditions are true or not(TRUE)
Here is a simple example of the VBA AND function. This below example macro checks two specified conditions. The output of below macro is TRUE.
'Check two conditions are true or not
Sub VBA_AND_Function_Ex1()
If (A = A) And (1 = 1) Then
MsgBox "Specified conditions are : TRUE ", vbInformation, "VBA AND Function"
Else
MsgBox "Specified conditions are : FALSE ", vbInformation, "VBA AND Function"
End If
End Sub
Output: Here is the screen shot of the first example output.
Example 2: Check two conditions are true or not(FALSE)
Here is a another example of the VBA AND function. This below example code checks two specified conditions. The output of below macro is FALSE.
'Check two conditions are true or not
Sub VBA_AND_Function_Ex2()
If (A = A) And (1 = 2) Then
MsgBox "Specified conditions are : TRUE ", vbInformation, "VBA AND Function"
Else
MsgBox "Specified conditions are : FALSE ", vbInformation, "VBA AND Function"
End If
End Sub
Output: Here is the screen shot of the second example output.
Example 3: Check two conditions are true or not(TRUE)
Here is a simple example of the VBA AND function. This below example macro checks three specified conditions. The output of below macro is TRUE.
'Check more than two conditions are true or not
Sub VBA_AND_Function_Ex3()
If (A = A) And (1 = 1) And (Z = Z) Then
MsgBox "Specified conditions are : TRUE ", vbInformation, "VBA AND Function"
Else
MsgBox "Specified conditions are : FALSE ", vbInformation, "VBA AND Function"
End If
End Sub
Output:Here is the screen shot of the third example output.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers







































