Return to VBA Code Examples

Using Conditional Formatting with Excel VBA

Excel Conditional Formatting

Excel Conditional Formatting allows you to define rules which determine cell formatting.

For example, you can create a rule that highlights cells that meet certain criteria. Examples include:

  • Numbers that fall within a certain range (ex. Less than 0).
  • The top 10 items in a list.
  • Creating a “heat map”.
  • “Formula-based” rules for virtually any conditional formatting.

In Excel, Conditional Formatting can be found in the Ribbon under Home > Styles (ALT  > H > L).

PIC 01

To create your own rule, click on ‘New Rule’ and a new window will appear:

PIC 02

Conditional Formatting in VBA

All of these Conditional Formatting features can be accessed using VBA.

Note that when you set up conditional formatting from within VBA code, your new parameters will appear in the Excel front-end conditional formatting window and will be visible to the user. The user will be able to edit or delete these unless you have locked the worksheet.

The conditional formatting rules are also saved when the worksheet is saved

Conditional formatting rules apply specifically to a particular worksheet and to a particular range of cells.  If they are needed elsewhere in the workbook, then they must be set up on that worksheet as well.


Practical Uses of Conditional Formatting in VBA

You may have a large chunk of raw data imported into your worksheet from a CSV (comma-separated values) file, or from a database table or query.  This may flow through into a dashboard or report, with changing numbers imported from one period to another.

Where a number changes and is outside an acceptable range, you may want to highlight this e.g. background color of the cell in red, and you can do this setting up conditional formatting. In this way, the user will be instantly drawn to this number, and can then investigate why this is happening.

You can use VBA to turn the conditional formatting on or off. You can use VBA to clear the rules on a range of cells, or turn them back on again. There may be a situation where there is a perfectly good reason for an unusual number, but when the user presents the dashboard or report to a higher level of management, they want to be able to remove the ‘alarm bells’.

Also, on the raw imported data, you may want to highlight where numbers are ridiculously large or ridiculously small. The imported data range is usually a different size for each period, so you can use VBA to evaluate the size of the new range of data and insert conditional formatting only for that range.

You may also have a situation where there is a sorted list of names with numeric values against each one e.g. employee salary, exam marks. With conditional formatting, you can use graduated colors to go from highest to lowest, which looks very impressive for presentation purposes.

However, the list of names will not always be static in size, and you can use VBA code to refresh the scale of graduated colors according to changes in the size of the range.


A Simple Example of Creating a Conditional Format on a Range

This example sets up conditional formatting for a range of cells (A1:A10) on a worksheet.  If the number in the range is between 100 and 150 then the cell background color will be red, otherwise it will have no color.

Notice that first we define the range MyRange to apply conditional formatting.

Next we delete any existing conditional formatting for the range. This is a good idea to prevent the same rule from being added each time the code is ran (of course it won’t be appropriate in all circumstances).

Colors are given by numeric values.  It is a good idea to use RGB (Red, Green, Blue) notation for this.  You can use standard color constants for this e.g. vbRed, vbBlue, but you are limited to eight color choices.

There are over 16.7M colors available, and using RGB you can access them all.  This is far easier than trying to remember which number goes with which color. Each of the three RGB color number is from 0 to 255.

Note that the ‘xlBetween’ parameter is inclusive so cell values of 100 or 150 will satisfy the condition.

Multi-Conditional Formatting

You may want to set up several conditional rules within your data range so that all the values in a range are covered by different conditions:

This example sets up the first rule as before, with the cell color of red if the cell value is between 100 and 150.

Two more rules are then added. If the cell value is less than 100, then the cell color is blue, and if it is greater than 150, then the cell color is yellow.

In this example, you need to ensure that all possibilities of numbers are covered, and that the rules do not overlap.

If blank cells are in this range, then they will show as blue, because Excel still takes them as having a value less than 100.

The way around this is to add in another condition as an expression.  This needs to be added as the first condition rule within the code. It is very important where there are multiple rules, to get the order of execution right otherwise results may be unpredictable.

This uses the type of xlExpression, and then uses a standard Excel formula to determine if a cell is blank instead of a numeric value.

The FormatConditions object is part of the Range object. It acts in the same way as a collection with the index starting at 1.  You can iterate through this object using a For…Next or For…Each loop.


Deleting a Rule

Sometimes, you may need to delete an individual rule in a set of multiple rules if it does not suit the data requirements.

This code creates a new rule for range A1:A10, and then deletes it.  You must use the correct index number for the deletion, so check on ‘Manage Rules’ on the Excel front-end (this will show the rules in order of execution) to ensure that you get the correct index number.  Note that there is no undo facility in Excel if you delete a conditional formatting rule in VBA, unlike if you do it through the Excel front-end.


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!!

Changing a Rule

Because the rules are a collection of objects based on a specified range, you can easily make changes to particular rules using VBA.  The actual properties once the rule has been added are read-only, but you can use the Modify method to change them. Properties such as colors are read / write.

This code creates a range object (A1:A10) and adds a rule for numbers between 100 and 150.  If the condition is true then the cell color changes to red.

The code then changes the rule to numbers less than 10. If the condition is true then the cell color now changes to green.

Using a Graduated Color Scheme

Excel conditional formatting has a means of using graduated colors on a range of numbers running in ascending or descending order.

This is very useful where you have data like sales figures by geographical area, city temperatures, or distances between cities. Using VBA, you have the added advantage of being able to choose your own graduated color scheme, rather than the standard ones offered on the Excel front-end.

When this code is run, it will graduate the cell colors according to the ascending values in the range A1:A10.

PIC 03

This is a very impressive way of displaying the data and will certainly catch the users’ attention.


Conditional Formatting for Error Values

When you have a huge amount of data, you may easily miss an error value in your various worksheets.  If this is presented to a user without being resolved, it could lead to big problems and the user losing confidence in the numbers.   This uses a rule type of xlExpression and an Excel function of IsError to evaluate the cell.

You can create code so that all cells with errors in have a cell color of red:

VBA Programming | Code Generator does work for you!

Conditional Formatting for Dates in the Past

You may have data imported where you want to highlight dates that are in the past.  An example of this could be a debtors’ report where you want any old invoice dates over 30 days old to stand out.

This code uses the rule type of xlExpression and an Excel function to evaluate the dates.

This code will take a range of dates in the range A1:A10, and will set the cell color to red for any date that is over 30 days in the past.

In the formula being used in the condition, Now() gives the current date and time.  This will keep recalculating every time the worksheet is recalculated, so the formatting will change from one day to the next.

Using Data Bars in VBA Conditional Formatting

You can use VBA to add data bars to a range of numbers.  These are almost like mini charts, and give an instant view of how large the numbers are in relation to each other.  By accepting default values for the data bars, the code is very easy to write.

Your data will look like this on the worksheet:

PIC 04

Using Icons in VBA conditional Formatting

You can use conditional formatting to put icons alongside your numbers in a worksheet.  The icons can be arrows or circles or various other shapes.  In this example, the code adds arrow icons to the numbers based on their percentage values:

This will give an instant view showing whether a number is high or low.  After running this code, your worksheet will look like this:

PIC 05

Using Conditional Formatting to Highlight Top Five

You can use VBA code to highlight the top 5 numbers within a data range.  You use a parameter called ‘AddTop10’, but you can adjust the rank number within the code to 5.  A user may wish to see the highest numbers in a range without having to sort the data first.

The data on your worksheet would look like this after running the code:

PIC 06

Note that the value of 145 appears twice so six cells are highlighted.


Significance of StopIfTrue and SetFirstPriority Parameters

StopIfTrue is of importance if a range of cells has multiple conditional formatting rules to it.  A single cell within the range may satisfy the first rule, but it may also satisfy subsequent rules. As the developer, you may want it to display the formatting only for the first rule that it comes to.  Other rule criteria may overlap and may make unintended changes if allowed to continue down the list of rules.

The default on this parameter is True but you can change it if you want all the other rules for that cell to be considered:

The SetFirstPriority parameter dictates whether that condition rule will be evaluated first when there are multiple rules for that cell.

This moves the position of that rule to position 1 within the collection of format conditions, and any other rules will be moved downwards with changed index numbers. Beware if you are making any changes to rules in code using the index numbers. You need to make sure that you are changing or deleting the right rule.

You can change the priority of a rule:

This will change the relative positions of any other rules within the conditional format list.


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

Using Conditional Formatting Referencing Other Cell Values

This is one thing that Excel conditional formatting cannot do. However, you can build your own VBA code to do this.

Suppose that you have a column of data, and in the adjacent cell to each number, there is some text that indicates what formatting should take place on each number.

The following code will run down your list of numbers, look in the adjacent cell for formatting text, and then format the number as required:

PIC 07

Once this code has been run, your worksheet will now look like this:

PIC 08

The cells being referred to for the formatting could be anywhere on the worksheet, or even on another worksheet within the workbook. You could use any form of text to make a condition for the formatting, and you are only limited by your imagination in the uses that you could put this code to.


Operators that can be used in Conditional formatting Statements

As you have seen in the previous examples, operators are used to determine how the condition values will be evaluated e.g. xlBetween.

There are a number of these operators that can be used, depending on how you wish to specify your rule criteria.

Name Value Description
xlBetween 1 Between. Can be used only if two formulas are provided.
xlEqual 3 Equal.
xlGreater 5 Greater than.
xlGreaterEqual 7 Greater than or equal to.
xlLess 6 Less than.
xlLessEqual 8 Less than or equal to.
xlNotBetween 2 Not between. Can be used only if two formulas are provided.
xlNotEqual 4 Not equal.