If and loop in excel vba

In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.

This is extremely valuable in many situations as we will see in the examples later in this tutorial.

To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.

The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).

In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.

But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

Syntax – IF Then Else

Below is the generic syntax of If Then Else construct in VBA

IF condition Then true_code [Else false_code]

Or

IF condition Then
true_code
Else
false_code
End IF

Note that the Else part of this statement is optional.

Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.

The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.

However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.

When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.

Hence you need to use the End IF statement.

In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”

IF Then Else in VBA- Block IF without End If error

Examples of Using IF Then Statement in VBA

To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).

Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).

Then you can use the following code:

Sub CheckScore()
If Range("A1").Value >=35 Then MsgBox "Pass"
End Sub

The above code has a single line of IF statement that checks the value in cell A1.

If it’s more than 35, it shows the message – “Pass”.

If it’s less than 35, nothing happens.

But what if you want to show a message in both the cases, whether a student passed or failed the exam.

The below code would do this:

Sub CheckScore()
If Range("A1").Value >= 35 Then
MsgBox "Pass"
Else
MsgBox "Fail"
End If
End Sub

The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).

But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.

Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.

Nested IF Then (Multiple IF Then statements)

So far we have used a single IF Then statement.

In case you have multiple conditions to check, you can use:

  • Multiple IF conditions
  • If Then Else statement
  • IF Then ElseIf Else construct

Let me show you how these differ and how to use this in Excel VBA.

Multiple IF Then Statements

Let’s take the same example of using a student’s score.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.

We can use the below code to get this done:

Sub CheckScore()
If Range("A1").Value < 35 Then MsgBox "Fail"
If Range("A1").Value >= 35 Then MsgBox "Pass"
End Sub

You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).

In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.

So even if the first IF statement is correct, the second would still be evaluated.

IF Then Else Statement

Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

We can use the below code to get this done:

Sub CheckScore()
If Range("A1").Value < 35 Then
MsgBox "Fail"
Else
If Range("A1").Value < 80 Then
MsgBox "Pass"
Else
MsgBox "Pass, with Distinction"
End If
End If
End Sub

In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.

So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.

IF Then ElseIf Else Statement

The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.

Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

Sub CheckScore()
If Range("A1").Value < 35 Then
MsgBox "Fail"
ElseIf Range("A1").Value < 80 Then
MsgBox "Pass"
Else
MsgBox "Pass, with Distinction"
End If
End Sub

The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.

Using AND and OR in IF Then Else

So far in this tutorial, we have only checked for a single condition at a time.

However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.

Below is the syntax of using AND/OR condition with the IF Then statement.

IF Condition1 AND Condition2 Then
true_code
Else
false_code
End IF

In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.

With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.

Now let’s see how AND and OR statement work with the IF Then Else construct.

Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:

  • Fail – When the score is less than 35 in any of the subjects.
  • Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
  • Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.

Here is the code that will do this:

Sub CheckScore()
If Range("A1").Value < 35 Or Range("B1").Value < 35 Then
MsgBox "Fail"
ElseIf Range("A1").Value < 80 And Range("B1").Value < 80 Then
MsgBox "Pass"
Else
MsgBox "Pass, with Distinction"
End If
End Sub

The above code uses both OR and AND statements.

You can also write this same code with a slight change (using OR instead of AND).

Sub CheckScore()
If Range("A1").Value < 35 Or Range("B1").Value < 35 Then
MsgBox "Fail"
ElseIf Range("A1").Value > 80 Or Range("B1").Value > 80 Then
MsgBox "Pass, with Distinction"
Else
MsgBox "Pass"
End If
End Sub

Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).

Using Not Equal to in If Then

In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.

You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.

To see a practical example of using <>, have a look at Example 1 below.

Using If Then Else with Loops in VBA

So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.

If I need to grade students, I can easily do that using Excel functions.

So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.

Example 1 – Save and Close All Workbooks Except The Active Workbook

If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,

Sub SaveCloseAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
On error resume next
If wb.Name <> ActiveWorkbook.Name Then
wb.Save
wb.Close
End If
Next wb
End Sub

The above code would save and close all the workbooks (except the active one).

It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.

If the name is not the same as that of the Active workbook, it saves and closes it.

In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).

Example 2 – Highlight Cells with Negative Values

Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.

Sub HighlightNegativeCells()
Dim Cll As Range
For Each Cll In Selection
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
Cll.Font.Color = vbWhite
End If
Next Cll
End Sub

The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.

Example 3 – Hide All the Worksheet Except the Current Worksheet

In case you want to quickly hide all the worksheets except the active one, you can use the below code:

Sub HideAllExceptActiveSheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> ActiveSheet.Name Then ws.Visible = xlSheetHidden
Next ws
End Sub

The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.

Example 4 – Extract the Numeric Part from an Alphanumeric String

If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:

Function GetNumeric(CellRef As String)
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetNumeric = Result
End Function

This code will create a custom function in Excel that can use within the worksheet (just like a regular function).

If Then Else in VBA - Custom Function

Where to Put the VBA Code?

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.IF Then Else in Excel VBA - Developer Tab in ribbon
  2. Click on Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.Insert Module in Excel VBA
  5. Copy and paste the code in the module window.If Then Else VBA Loop - code in the Vb Editor

You May Also Like the Following Excel Tutorials:

  • How to Record a Macro in Excel.
  • Working with Cells and Ranges in Excel VBA.
  • Working with Worksheets in Excel VBA.
  • Working with Workbooks in Excel VBA.
  • Creating a Custom Function in Excel Using VBA.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • Excel VBA MsgBox
  • How to Run a Macro in Excel.
  • How to Create and Use an Excel Add-in.
  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
  • Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).

Содержание

  1. If Then Else Statement in Excel VBA (explained with examples)
  2. Syntax – IF Then Else
  3. Examples of Using IF Then Statement in VBA
  4. Nested IF Then (Multiple IF Then statements)
  5. Multiple IF Then Statements
  6. IF Then Else Statement
  7. IF Then ElseIf Else Statement
  8. Using AND and OR in IF Then Else
  9. Using Not Equal to in If Then
  10. Using If Then Else with Loops in VBA
  11. Example 1 – Save and Close All Workbooks Except The Active Workbook
  12. Example 2 – Highlight Cells with Negative Values
  13. Example 3 – Hide All the Worksheet Except the Current Worksheet
  14. Example 4 – Extract the Numeric Part from an Alphanumeric String
  15. Where to Put the VBA Code?
  16. VBA If, ElseIf, Else (Ultimate Guide to If Statements)
  17. VBA If Statement
  18. If Then
  19. End If
  20. ElseIF – Multiple Conditions
  21. If-Else
  22. Nested IFs
  23. VBA Coding Made Easy
  24. IF – Or, And, Xor, Not
  25. If Or
  26. If And
  27. If Xor
  28. If Not
  29. If Comparisons
  30. Comparing Text
  31. VBA If Like
  32. If Loops
  33. If Else Examples
  34. Check if Cell is Empty
  35. Check if Cell Contains Specific Text
  36. Check if cell contains text
  37. If Goto
  38. Delete Row if Cell is Blank
  39. If MessageBox Yes / No
  40. VBA If, ElseIf, Else in Access VBA
  41. VBA Code Examples Add-in

If Then Else Statement in Excel VBA (explained with examples)

In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.

This is extremely valuable in many situations as we will see in the examples later in this tutorial.

To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.

The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).

In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.

But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

This Tutorial Covers:

Syntax – IF Then Else

Below is the generic syntax of If Then Else construct in VBA

Note that the Else part of this statement is optional.

Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.

The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.

However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.

When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.

Hence you need to use the End IF statement.

In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”

Examples of Using IF Then Statement in VBA

To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).

Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).

Then you can use the following code:

The above code has a single line of IF statement that checks the value in cell A1.

If it’s more than 35, it shows the message – “Pass”.

If it’s less than 35, nothing happens.

But what if you want to show a message in both the cases, whether a student passed or failed the exam.

The below code would do this:

The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).

But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.

Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.

Nested IF Then (Multiple IF Then statements)

So far we have used a single IF Then statement.

In case you have multiple conditions to check, you can use:

  • Multiple IF conditions
  • If Then Else statement
  • IF Then ElseIf Else construct

Let me show you how these differ and how to use this in Excel VBA.

Multiple IF Then Statements

Let’s take the same example of using a student’s score.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.

We can use the below code to get this done:

You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).

In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.

So even if the first IF statement is correct, the second would still be evaluated.

IF Then Else Statement

Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.

If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

We can use the below code to get this done:

In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.

So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.

IF Then ElseIf Else Statement

The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.

Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.

The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.

Using AND and OR in IF Then Else

So far in this tutorial, we have only checked for a single condition at a time.

However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.

Below is the syntax of using AND/OR condition with the IF Then statement.

In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.

With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.

Now let’s see how AND and OR statement work with the IF Then Else construct.

Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:

  • Fail – When the score is less than 35 in any of the subjects.
  • Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
  • Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.

Here is the code that will do this:

The above code uses both OR and AND statements.

You can also write this same code with a slight change (using OR instead of AND).

Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).

Using Not Equal to in If Then

In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.

You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.

To see a practical example of using <>, have a look at Example 1 below.

Using If Then Else with Loops in VBA

So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.

If I need to grade students, I can easily do that using Excel functions.

So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.

Example 1 – Save and Close All Workbooks Except The Active Workbook

If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,

The above code would save and close all the workbooks (except the active one).

It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.

If the name is not the same as that of the Active workbook, it saves and closes it.

In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).

Example 2 – Highlight Cells with Negative Values

Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.

The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.

Example 3 – Hide All the Worksheet Except the Current Worksheet

In case you want to quickly hide all the worksheets except the active one, you can use the below code:

The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.

If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:

This code will create a custom function in Excel that can use within the worksheet (just like a regular function).

Where to Put the VBA Code?

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.
  2. Click on Visual Basic option. This will open the VB editor in the backend.
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.
  5. Copy and paste the code in the module window.

You May Also Like the Following Excel Tutorials:

Источник

VBA If, ElseIf, Else (Ultimate Guide to If Statements)

In this Article

VBA If Statement

If Then

VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.

Let’s look at a simple example:

This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”

Note: When testing conditions we will use the =, >, , = comparison operators. We will discuss them in more detail later in the article.

Here is the syntax for a simple one-line If statement:

To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):

End If

The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:

Here the syntax is:

The End If signifies the end of the if statement.

Now let’s add in an ElseIF:

ElseIF – Multiple Conditions

The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.

In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:

You can use multiple ElseIfs to test for multiple conditions:

Now we will add an Else:

The Else will run if no other previous conditions have been met.

We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:

If-Else

The most common type of If statement is a simple If-Else:

Nested IFs

You can also “nest” if statements inside of each other.

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!

IF – Or, And, Xor, Not

Next we will discuss the logical operators: Or, And, Xor, Not.

If Or

The Or operator tests if at least one condition is met.

The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:

You can include multiple Ors in one line:

If you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:

If And

The And operator allows you to test if ALL conditions are met.

If Xor

The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.

I’ve rarely seen Xor used in VBA programming.

If Not

The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:

Notice that the Not operator requires parenthesis surrounding the expression to switch.

The Not operator can also be applied to If statements:

If Comparisons

When making comparisons, you will usually use one of the comparison operators:

Comparison Operator Explanation
= Equal to
<> Not Equal to
> Greater than
>= Greater than or Equal to
If – Boolean Function

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.

Источник

Adblock
detector

Skip to content

Conditional Statements in Excel VBA – If Else, Case, For, Do While, Do Until, Nested Ifs

Home » Excel VBA » Conditional Statements in Excel VBA – If Else, Case, For, Do While, Do Until, Nested Ifs

  • procedures in excel vba

Conditional Statements in Excel VBA are very useful in programming, this will give you to perform comparisons to decide or loop through certain number of iterations based on a criteria. In this tutorial we will learn the conditional statements with examples.

Conditional Statements in Excel VBA

    In this tutorial:

  • » IF Statement
  • » If … Else Statement
  • » If … ElseIf … Else Statement
  • » If … ElseIf … ElseIf Statement
  • » Nested If Statement

Conditional Statements in Excel VBA – Download: Example File

Download this example file, we will learn conditional statements with examples.
ANALYSISTABS Examples on Conditional Statements

IF Statement
If .. Then

Syntax:

If <Condition> Then <Statement>

It is a simple Condition to check an expression, if the condition is True it will execute the Statement.

Sub sb1_IFCondition()

     'Check if cell(C2)is greater than 6Lakhs
     If Range("C2") > 600000 Then Range("D2") = Range("C2") * 10 / 100

End Sub

(OR)

Sub sb1_IFCondition()
     
     'Check if cell(C2)is greater than 6Lakhs
     If Range("C2") > 600000 Then        
         Range("D2") = Range("C2") * 10 / 100
     end if

End Sub

It will check if the range C2 value, if it is greater than 600000 it will execute the statement ‘Range(“D2”) = Range(“C2”) * 10 / 100’.

If … Else Statement

Syntax:

If <Condition> Then
   Statements1
Else
   Statements2
End if

It will check the Condition, if the condition is True it will execute the Statements1, if False execute the Statements2.

Example 1: Check whether the cell number is greater than six lakhs
Sub If_Else1()

If Range("B2") > 600000 Then
    Range("D2") = Range("C2") * 5 / 100
Else
    Range("D2") = Range("C2") * 10 / 100
End If

End Sub
Example 2: Check whether the number is even or odd
Sub If_Else2()
    
    'Variable declaration
    Dim Num As Integer
    
    'Accepting the number by the user
    Num = InputBox("Enter the Number:", "Number")
        
    If Num Mod 2 = 0 Then
        'Check whether the number is even
        MsgBox "Entered number is Even."
    Else
        'Check whether the number is odd
        MsgBox "Entered number is Odd."
    End If

End Sub
If … ElseIf … Else Statement

You can use If…ElseIf…Else to check more conditions:

If Condition1 Then
    Statements1
ElseIf Condition2 Then
    Statements2
Else
    StatementsN
End If
Example : Check whether the number entered by the user is positive, negative or equal to zero.
Sub If_ElseIf_Else()
    
    'Variable declaration
    Dim Num As Integer
    
    'Accepting the number by the user
    Num = InputBox("Enter the Number:", "Number")
        
    If Num < 0 Then
        'Check whether the number is less  than zero
        MsgBox "Number is negative."
    ElseIf Num = 0 Then
        'Check whether the number is equal to zero
        MsgBox "Number is zero."
    Else
        'Check whether the number is greater  than zero
        MsgBox "Number is positive."
    End If

End Sub
If … ElseIf … ElseIf Statement

You can use If…ElseIf…ElseIf to check more conditions:

If Condition1 Then
    Statements1
ElseIf Condition2 Then
    Statements2
ElseIf ConditionN Then
    StatementsN
End If
Example : Check whether the number entered by the user is positive, negative or equal to zero.
Sub If_ElseIf_ElseIf()
    
    'Variable declaration
    Dim Num As Integer
    
    'Accepting the number by the user
    Num = InputBox("Enter the Number:", "Number")
        
    If Num < 0 Then
        'Check whether the number is less  than zero
        MsgBox "Number is negative."
    ElseIf Num = 0 Then
        'Check whether the number is equal to zero
        MsgBox "Number is zero."
    ElseIf Num > 0 Then
        'Check whether the number is greater  than zero
        MsgBox "Number is positive."
    End If

End Sub
Nested If Statement

You can use If…ElseIf…ElseIf…ElseIf…Else to check more conditions:

If Condition1 Then
    Statements1
ElseIf Condition2 Then
    Statements2
ElseIf Condition3 Then
    Statements3

    ...........

ElseIf ConditionN Then
    StatementsN
End If
Example 1: Check if the month is fall under which quater using “Nested If” statement and “OR” Operator
Sub NestedIf_FindQuater()
    
    'Variable declaration
    Dim Mnt As String
    
    'Accepting the month by the user
    Mnt = InputBox("Enter the Month:", "Month")
        
    If Mnt = "January" Or Mnt = "February" Or Mnt = "March" Then
        'Check if the month is fall under first quater.
        MsgBox "First Quater."
    ElseIf Mnt = "April" Or Mnt = "May" Or Mnt = "June" Then
        'Check if the month is fall under second quater.
        MsgBox "Second Quater."
    ElseIf Mnt = "July" Or Mnt = "August" Or Mnt = "September" Then
        'Check if the month is fall under third quater.
        MsgBox "Third Quater."
    Else
        'Check if the month is fall under fourth quater.
        MsgBox "Fourth Quater."
    End If

End Sub
Example : Check Student Grade based on Marks using “Nested If” statement and “AND” operator
Sub NestedIf_StudentGrade()
    
    'Variable declaration
    Dim Mrks As String
    
    'Accepting the month by the user
    Mrks = InputBox("Enter the Marks:", "Marks")
        
    If Mrks <= 100 And Mrks >= 90 Then
        'Check if the Grade A++
        MsgBox "Grade : A++"
    ElseIf Mrks < 90 And Mrks >= 80 Then
        'Check if the Grade A+
        MsgBox "Grade : A+"
    ElseIf Mrks < 80 And Mrks >= 60 Then
        'Check if the Grade A
        MsgBox "Grade : A"
    ElseIf Mrks < 60 And Mrks >= 50 Then
        'Check if the Grade B
        MsgBox "Grade : B"
    ElseIf Mrks < 50 And Mrks >= 35 Then
        'Check if the Grade C
        MsgBox "Grade : C"
    Else
        'Check if the Grade has fail
        MsgBox "Grade : Fail"
    End If

End Sub
Select … Case

If you have a more number of conditions to check, the If condition will go through each one of them. The alternative of jumping to the statement that applies to the state of a condition is Select Case.

Syntax:

Select Case Expression
    Case Expression1
	Statement1
    Case Expression2
        Statement2
    Case ExpressionN
        StatementN
End Select 

Following is the example on select case:

Sub sb3_SelectCaseCondition()
Select Case Range("B2")
    Case "D1"
    Range("D2") = Range("C2") * 10 / 100
    Case "D2"
    Range("D2") = Range("C2") * 20 / 100
    Case "D3", "D4"
    Range("D2") = Range("C2") * 15 / 100
    Case Else
    Range("D2") = Range("C2") * 5 / 100
End Select
End Sub
Loops

You can use loops to execute statements certain number of time or until it satisfies some condtion.

For Loop

For loop is useful to execute statements certain number of time.

Syntax:

For CounterVariable = Starting Number To Ending Number
  Statements
Next

The following example show you the message box 5 times with integers

Sub sbForLoop()
Dim iCntr  As Integer
For iCntr = 1 To 5
    msgbox iCntr
Next
End Sub

Following is another Example on For Loop:

Sub sb4_ForLoop()
Dim iCntr  As Integer
For iCntr = 2 To 16
    Cells(iCntr, 4) = Cells(iCntr, 3) * 10 / 100
Next
End Sub

You can use Step statement to stepping the counter.

Sub sbForLoop()
Dim iCntr  As Integer
For iCntr = 1 To 10 Step 2
    msgbox iCntr
Next
End Sub

By default the stepping counter is 1, the below two statements are same:
1. For iCntr = 1 To 10
2. For iCntr = 1 To 10 Step 1

For Each Item In the Loop

If you want to loop through a collection, you can use for each condition. The following example loop through the Sheets collection of the Workbook.

Sub sbForEachLoop()
Dim Sht As Worksheet
For Each Sht In ThisWorkbook.Sheets
    MsgBox Sht.Name
Next
End Sub
Do…While

Do loop is a technique used to repeat an action based on a criteria.

Syntax:

Do While Condition
  Statement(s)
Loop

It will execute the statements if the condition is true,The following is example on Dow While:

Sub sb5_DoWhileLoop()
Dim iCntr  As Integer
iCntr = 2
Do While Cells(iCntr, 3) <> ""
    Cells(iCntr, 4) = Cells(iCntr, 3) * 10 / 100
    iCntr = iCntr + 1
Loop
End Sub

Other flavors of the Do loop:

Do
    Statement(s)
Loop While Condition

'-------------------------------

Do
    Statements
Loop Until Condition

'-------------------------------

Do Until Condition
    Statement(s)
Loop

Exiting in between Loops and Procedure

You can Exit the For loop in between based on a condition using Exit For

In the following, it will exit the is for loop if the sheet name is equals to “Data”

Sub sbForEachLoop()
Dim Sht As Worksheet
For Each Sht In ThisWorkbook.Sheets
    MsgBox Sht.Name
    if Sht.Name="Data" then Exit For
Next
End Sub

You can Exit any Procedure using Exit Sub

In the following, it will exit the procedure if the sheet name is equals to “Data”

Sub sbForEachLoop()
Dim Sht As Worksheet
For Each Sht In ThisWorkbook.Sheets
    MsgBox Sht.Name
    if Sht.Name="Data" then Exit Sub
Next
End Sub

You can Exit Exiting a Do Loop using Exit Do

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • Conditional Statements in Excel VBA – Download: Example File
      • You can use Step statement to stepping the counter.
      • You can Exit the For loop in between based on a condition using Exit For
      • You can Exit any Procedure using Exit Sub
      • You can Exit Exiting a Do Loop using Exit Do

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

6 Comments

  1. I read a lot of interesting articles here. Probably you
    spend a lot of time writing, i know how to save you a lot of time, there is an online tool
    that creates high quality, SEO friendly articles in minutes, just search
    in google – laranitas free content source

  2. Daniel Hill
    May 6, 2015 at 2:36 AM — Reply

    Can you tell me why this code doesn’t work? I can’t get a For … Next or other versions to work either. For this code I get the following error message “Code execution has been interrupted”. Debug shows the problem is on the iCtr = iCtr + 1 line. Value in Cell(102,4) is dependent on value in cell (102,7).

    iCtr = 1
    Do Until Cells(102, 4) < 100
    Cells(102, 7) = iCtr
    iCtr = iCtr + 1
    Loop

  3. Daniel Hill
    May 6, 2015 at 2:45 AM — Reply
  4. Abhishek
    June 28, 2015 at 5:07 PM — Reply

    Please add some examples of do until loop..

  5. krishna singh
    July 26, 2015 at 9:06 PM — Reply

    Hi Sir,

    I am Trying to create a VBA for the Bank reconciliation Statement though some what i have succeed by viewing your clips but stuck in one problem
    if suppose there are 2 sheets such as sheet 1 and sheet 2 . if chq and amount matched so how would we give the sr no in the both sheet which should be same and for the next match it should give other no

    Regards
    Krishna

  6. Ruchi Sharma
    January 12, 2018 at 4:47 PM — Reply

    Hi,

    could you please help me out with the VBA code for a data which is in column A with numbers that starts from 1,2,3,4…
    how can using VBA i can get numbers that starts from 1 and 2 stated as ‘balance sheet’ in column B

    so in short i want data in column B from A basis some condition and that condition is that number in column A should starts from 1 and 2 only.
    Please help!

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

In this Article

  • VBA If Statement
    • If Then
  • ElseIF – Multiple Conditions
  • Else
  • If-Else
  • Nested IFs
  • IF – Or, And, Xor, Not
    • If Or
    • If And
    • If Xor
    • If Not
  • If Comparisons
    • If – Boolean Function
    • Comparing Text
    • VBA If Like
  • If Loops
  • If Else Examples
    • Check if Cell is Empty
    • Check if Cell Contains Specific Text
    • Check if cell contains text
    • If Goto
    • Delete Row if Cell is Blank
    • If MessageBox Yes / No
  • VBA If, ElseIf, Else in Access VBA

VBA If Statement

vba else if statement

If Then

VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.

Let’s look at a simple example:

If Range("a2").Value > 0 Then Range("b2").Value = "Positive"

This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”

vba if then

Note: When testing conditions we will use the =, >, <, <>, <=, >= comparison operators. We will discuss them in more detail later in the article.

Here is the syntax for a simple one-line If statement:

If [test_expression] then [action]

To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):

If [test_expression] then _
    [action]
If Range("a2").Value > 0 Then _
   Range("b2").Value = "Positive"

End If

The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:

If Range("a2").Value > 0 Then
  Range("b2").Value = "Positive"
End If

vba end if

Here the syntax is:

If [test_expression] then
  [action]
End If

The End If signifies the end of the if statement.

Now let’s add in an ElseIF:

ElseIF – Multiple Conditions

The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.

In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
End If

vba elseif

You can use multiple ElseIfs to test for multiple conditions:

Sub If_Multiple_Conditions()

    If Range("a2").Value = "Cat" Then
        Range("b2").Value = "Meow"
    ElseIf Range("a2").Value = "Dog" Then
        Range("b2").Value = "Woof"
    ElseIf Range("a2").Value = "Duck" Then
        Range("b2").Value = "Quack"
    End If

End Sub

Now we will add an Else:

Else

The Else will run if no other previous conditions have been met.

We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
Else
    Range("b2").Value = "Zero"
End If

vba else

If-Else

The most common type of If statement is a simple If-Else:

Sub If_Else()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        Range("b2").Value = "Not Positive"
    End If
End Sub

vba if else

Nested IFs

You can also “nest” if statements inside of each other.

Sub Nested_Ifs()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        If Range("a2").Value < 0 Then
            Range("b2").Value = "Negative"
        Else
            Range("b2").Value = "Zero"
        End If
    End If
End Sub

nested ifs

VBA Coding Made Easy

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

automacro

Learn More

IF – Or, And, Xor, Not

Next we will discuss the logical operators: Or, And, Xor, Not.

If Or

The Or operator tests if at least one condition is met.

The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Then
    Range("b2").Value = "Out of Range"
End If

if or

You can include multiple Ors in one line:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Or Range("a2").Value = 9999 Then
    Range("b2").Value = "Out of Range"
End If

If you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:

If Range("a2").Value < 5000 Or _
   Range("a2").Value > 10000 Or _
   Range("a2").Value = 9999 Then

       Range("b2").Value = "Out of Range"
End If

vba multiple ors

If And

The And operator allows you to test if ALL conditions are met.

If Range("a2").Value >= 5000 And Range("a2").Value <= 10000 Then
    Range("b2").Value = "In Range"
End If

vba if and

VBA Programming | Code Generator does work for you!

If Xor

The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.

I’ve rarely seen Xor used in VBA programming.

If Not

The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:

Sub IF_Not()
    MsgBox Not (True)
End Sub

vba if not

Notice that the Not operator requires parenthesis surrounding the expression to switch.

The Not operator can also be applied to If statements:

If Not (Range("a2").Value >= 5000 And Range("a2").Value <= 10000) Then
    Range("b2").Value = "Out of Range"
End If

if not

If Comparisons

When making comparisons, you will usually use one of the comparison operators:

Comparison Operator Explanation
= Equal to
<> Not Equal to
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to

However, you can also use any expression or function that results in TRUE or FALSE

If – Boolean Function

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:

If IsEmpty(Range("A1").Value) Then MsgBox "Cell Empty"

Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:

If Application.WorksheetFunction.IsText(Range("a2").Value) Then _ 
   MsgBox "Cell is Text"

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:

Sub If_Function()

If TrueFunction Then
    MsgBox "True"
End If

End Sub

Function TrueFunction() As Boolean
    TrueFunction = True
End Function

vba if boolean function

Comparing Text

You can also compare text similar to comparing numbers:

Msgbox "a" = "b"
Msgbox "a" = "a"

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:

Option Compare Text

After making that declaration “A” = “a”:

Option Compare Text

Sub If_Text()
   MsgBox "a" = "A"
End Sub

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

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:

Dim strName as String
strName = "Mr. Charles"

If strName Like "Mr*" Then
    MsgBox "True"
Else
    MsgBox "False"
End If

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:

Sub If_Loop()
Dim Cell as Range

  For Each Cell In Range("A2:A6")
    If Cell.Value > 0 Then
      Cell.Offset(0, 1).Value = "Positive"
    ElseIf Cell.Value < 0 Then
      Cell.Offset(0, 1).Value = "Negative"
    Else
      Cell.Offset(0, 1).Value = "Zero"
     End If
  Next Cell

End Sub

vba else if statement

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:

Sub If_Cell_Empty()

If Range("a2").Value <> "" Then
    Range("b2").Value = Range("a2").Value
End If

End Sub

vba if cell empty do nothing

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

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:

If Instr(Range("A2").value,"text") > 0 Then
  Msgbox "Text Found"
End If

Check if cell contains text

This code will test if a cell is text:

Sub If_Cell_Is_Text()

If Application.WorksheetFunction.IsText(Range("a2").Value) Then
    MsgBox "Cell is Text"
End If

End Sub

If Goto

You can use the result of an If statement to “Go to” another section of code.

Sub IfGoTo ()

    If IsError(Cell.value) Then
        Goto Skip
    End If

    'Some Code

Skip:
End Sub

Delete Row if Cell is Blank

Using Ifs and loops you can test if a cell is blank and if so delete the entire row.

Sub DeleteRowIfCellBlank()

Dim Cell As Range

For Each Cell In Range("A2:A10")
    If Cell.Value = "" Then Cell.EntireRow.Delete
Next Cell

End Sub

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

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 yes no msgbox

Sub MsgBoxVariable()

Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

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 yes no msgbox

The IF…THEN statement is one of the most commonly used and most useful statements in VBA.  The IF…THEN statement allows you to build logical thinking inside your macro.

The IF…THEN statement is like the IF function in Excel.  You give the IF a condition to test, such as “Is the customer a “preferred” customer?”  If the customer is classified as “preferred” then calculate a discount amount.  Another test could be to test the value of a cell, such as “Is the cell value greater than 100?”  If so, display the message “Great sale!”  Otherwise, display the message “Better luck next time.”

The IF…THEN can also evaluate many conditions.  Like the AND function, you can ask several questions and all the questions must evaluate to TRUE to perform the action.  Similarly, you can ask several questions and if any single or multiple of questions are true, the action will be performed.  This is like an OR function in Excel.

Task #1 – Simple IF

In this example we will evaluate a single cell.  Once we have the logic correct, we will apply the logic to a range of cells using a looping structure.

In Excel, open the VBA Editor by pressing F-11 (or press the Visual Basic button on the Developer ribbon.)

Right-click “This Workbook” in the Project Explorer (upper-left of VBA Editor) and select Insert ⇒ Module.

In the Code window (right panel) type the following and press ENTER.

Sub Simple_If()

We want to evaluate the contents of cell B9 to determine if the value is greater than 0 (zero).  If the value is >0, we will display the value of cell B9 in cell C9.

In the Code window, click between the Sub and End Sub commands and enter the following.

If Range("B9").Value > 0 Then Range("C9").Value = Range("B9").Value

If you only have a single action to perform, you can leave all the code on a single line and you do not have to close the statement with an END IF.

If you have more than one action to perform, you will want to break your code into multiple lines like the following example.

When using this line-break style, don’t forget to include the END IF statement at the end of the logic.

Test the function by executing the macro.  Click in the code and press F5 or click the Run  button on the toolbar at the top of the VBA Editor window.

The number 45 should appear in cell C9.

If we change the value in cell B9 to -2, clear the contents of cell C9 and re-run the macro, cell C9 will remain blank.

Suppose we want to test the values in Column B to see if they are between 1 and 400.  We will use an AND statement to allow the IF to perform multiple tests.

Update the code with the following IF statement.

Sub Simple_If()
	If Range("B9").Value > 0 And Range("B9").Value <= 400 Then
		Range("C9").Value = Range("B9").Value
	End If
End Sub

Test the macro by changing the value in cell B9 to values between 1 and 400 as well as testing values >400 or <=0 (remember to clear the contents of cell C9 prior to each test).

Task #2 – Color all values between 1 and 400 green (Looping Through Data)

Now we want to loop through the values in Column B and perform the test on each value.

Below the existing procedure, start a new procedure named IF_Loop().  Type the following and press ENTER.

Sub IF_Loop()

We want to color all the cells in range B9:B18 green if their cell value is between 1 and 400.

There are many ways to determine the data’s range.  For examples of several range detection/selection techniques, click the link below to check out the VBA & Macros course.

Unlock Excel VBA and Excel Macros

The technique we will use is to convert the plain table to a Data Table and use Table References.  Table References are great because they automatically expand and contract when data is either added or removed from the table.  This keep you from having to update all your formulas and VBA code when data ranges change, which they often do.

Click anywhere in the table and press CTRL-T and then click OK.

We want to restore our original cell colors.  Select Table Tools ⇒ Design ⇒ Table Styles (group) ⇒ Expand the table styles list and select Clear (bottom of list).

Rename the table (upper-left) to “TableSales”.

Select cell D7 (or any blank cell) and type an equal’s sign.

=

Select cells B9:B18 and note the update to the formula.  This contains the proper method for referring to table fields (columns).

=TableSales[Sales]

Highlight the reference in the formula bar (do not include the equal’s sign) and press CTRL-C to copy the reference into memory.

Press ESC to abandon the formula.

Return to the VBA Editor and click between the Sub and End Sub commands in the IF_Loop() procedure.

We want to loop through the sales column of the table.  For detailed information on creating and managing looping structures, click the link below.

Excel VBA: Loop through cells inside the used range (For Each Collection Loop)

We want the cell color to change to green if the cell’s value is between 1 and 400.  We can use the Interior object to set the Color property to green.  Enter the following code in the VBA Editor.

Sub IF_Loop()
	Dim cell As Range
	For Each cell In Range("TableSales[Sales]")
		If cell.Value > 0 And cell.Value <= 400 Then
			cell.Interior.Color = VBA.ColorConstants.vbGreen
		End If
	Next cell
End Sub

Run the updated code to see the results as witnessed below.

The color green is a bit on the bright side.  We want a pale green, but we don’t know the color code for pale green.  Here is a great way to discover the color of any cell.

Open the Immediate Windows by pressing CTRL-G or clicking View à Immediate Window from the VBA Editor toolbar.  This should present the Immediate Window in the lower portion of the VBA Editor.

Select an empty cell and set the fill color to a pale green.

With the newly colored cell selected, click in the Immediate Window of the VBA Editor and enter the following text and press ENTER.

 ? activecell.Interior.Color

The above command will return the value of the active cell’s fill color.  In this case, pale green is 9359529.

Update the VBA code to use the color code for pale green instead of the VBA green.

 cell.Interior.Color = 9359529

Run the updated code and notice the colors are a more pleasant pale green.

Task #3 – Color all cells that are <=0 and >400 yellow

Now that we have identified all the numbers between 1 and 400, let’s color the remaining cells yellow.  The color code for the yellow we will be using is 6740479.

To add the second possible action will require the addition of an ELSE statement at the end of our existing IF statement.  Update the code with the following modification.

  Else
    cell.Interior.Color = 6740479

Run the updated code and notice how all the previously white cells are now yellow.

Task #4 – Negative values will be colored red

We will now update the code to color all the negative valued cells red.  The color code for the red we will be using is 192.

To add the third possible action will require the addition of an ELSEIF statement directly after the initial IF statement.  Update the code with the following modification.

 ElseIf cell.Value < 0 Then
     cell.Interior.Color = 192

Run the updated macro and observe that all the negative valued cells are now filled with the color red.

Feel free to Download the Workbook HERE.

Free Excel Download

Published on: August 23, 2018

Last modified: February 21, 2023

Microsoft Most Valuable Professional

Leila Gharani

I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.

My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.

Понравилась статья? Поделить с друзьями:
  • If and iserror excel
  • If formula excel 2016
  • If and index function in excel
  • If formula advanced excel
  • If and iferror in excel