In this Article
- Excel Conditional Formatting
- Conditional Formatting in VBA
- Practical Uses of Conditional Formatting in VBA
- A Simple Example of Creating a Conditional Format on a Range
- Multi-Conditional Formatting
- Deleting a Rule
- Changing a Rule
- Using a Graduated Color Scheme
- Conditional Formatting for Error Values
- Conditional Formatting for Dates in the Past
- Using Data Bars in VBA Conditional Formatting
- Using Icons in VBA Conditional Formatting
- Using Conditional Formatting to Highlight Top Five
- Significance of StopIfTrue and SetFirstPriority Parameters
- Using Conditional Formatting Referencing Other Cell Values
- Operators that can be used in Conditional formatting Statements
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).
To create your own rule, click on ‘New Rule’ and a new window will appear:
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.
Sub ConditionalFormattingExample() ‘Define Range Dim MyRange As Range Set MyRange = Range(“A1:A10”) ‘Delete Existing Conditional Formatting from Range MyRange.FormatConditions.Delete ‘Apply Conditional Formatting MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _ Formula1:="=100", Formula2:="=150" MyRange.FormatConditions(1).Interior.Color = RGB(255, 0, 0) End Sub
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:
Sub MultipleConditionalFormattingExample() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add first rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _ Formula1:="=100", Formula2:="=150" MyRange.FormatConditions(1).Interior.Color = RGB(255, 0, 0) 'Add second rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="=100" MyRange.FormatConditions(2).Interior.Color = vbBlue 'Add third rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="=150" MyRange.FormatConditions(3).Interior.Color = vbYellow End Sub
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.
Sub MultipleConditionalFormattingExample() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add first rule MyRange.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=LEN(TRIM(A1))=0" MyRange.FormatConditions(1).Interior.Pattern = xlNone 'Add second rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _ Formula1:="=100", Formula2:="=150" MyRange.FormatConditions(2).Interior.Color = RGB(255, 0, 0) 'Add third rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="=100" MyRange.FormatConditions(3).Interior.Color = vbBlue 'Add fourth rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="=150" MyRange.FormatConditions(4).Interior.Color = RGB(0, 255, 0) End Sub
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.
Sub DeleteConditionalFormattingExample() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add first rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _ Formula1:="=100", Formula2:="=150" MyRange.FormatConditions(1).Interior.Color = RGB(255, 0, 0) 'Delete rule MyRange.FormatConditions(1).Delete End Sub
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!
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.
Sub ChangeConditionalFormattingExample() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add first rule MyRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _ Formula1:="=100", Formula2:="=150" MyRange.FormatConditions(1).Interior.Color = RGB(255, 0, 0) 'Change rule MyRange.FormatConditions(1).Modify xlCellValue, xlLess, "10" ‘Change rule color MyRange.FormatConditions(1).Interior.Color = vbGreen End Sub
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.
Sub GraduatedColors() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Define scale type MyRange.FormatConditions.AddColorScale ColorScaleType:=3 'Select color for the lowest value in the range MyRange.FormatConditions(1).ColorScaleCriteria(1).Type = _ xlConditionValueLowestValue With MyRange.FormatConditions(1).ColorScaleCriteria(1).FormatColor .Color = 7039480 End With 'Select color for the middle values in the range MyRange.FormatConditions(1).ColorScaleCriteria(2).Type = _ xlConditionValuePercentile MyRange.FormatConditions(1).ColorScaleCriteria(2).Value = 50 'Select the color for the midpoint of the range With MyRange.FormatConditions(1).ColorScaleCriteria(2).FormatColor .Color = 8711167 End With 'Select color for the highest value in the range MyRange.FormatConditions(1).ColorScaleCriteria(3).Type = _ xlConditionValueHighestValue With MyRange.FormatConditions(1).ColorScaleCriteria(3).FormatColor .Color = 8109667 End With End Sub
When this code is run, it will graduate the cell colors according to the ascending values in the range A1:A10.
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:
Sub ErrorConditionalFormattingExample() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add error rule MyRange.FormatConditions.Add Type:=xlExpression, Formula1:="=IsError(A1)=true" 'Set interior color to red MyRange.FormatConditions(1).Interior.Color = RGB(255, 0, 0) End Sub
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.
Sub DateInPastConditionalFormattingExample() Dim MyRange As Range 'Create range object based on a column of dates Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add error rule for dates in past MyRange.FormatConditions.Add Type:=xlExpression, Formula1:="=Now()-A1 > 30" 'Set interior color to red MyRange.FormatConditions(1).Interior.Color = RGB(255, 0, 0) End Sub
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.
Sub DataBarFormattingExample() Dim MyRange As Range Set MyRange = Range(“A1:A10”) MyRange.FormatConditions.Delete MyRange.FormatConditions.AddDatabar End Sub
Your data will look like this on the worksheet:
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:
Sub IconSetsExample() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add Icon Set to the FormatConditions object MyRange.FormatConditions.AddIconSetCondition 'Set the icon set to arrows - condition 1 With MyRange.FormatConditions(1) .IconSet = ActiveWorkbook.IconSets(xl3Arrows) End With 'set the icon criteria for the percentage value required - condition 2 With MyRange.FormatConditions(1).IconCriteria(2) .Type = xlConditionValuePercent .Value = 33 .Operator = xlGreaterEqual End With 'set the icon criteria for the percentage value required - condition 3 With MyRange.FormatConditions(1).IconCriteria(3) .Type = xlConditionValuePercent .Value = 67 .Operator = xlGreaterEqual End With End Sub
This will give an instant view showing whether a number is high or low. After running this code, your worksheet will look like this:
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.
Sub Top5Example() Dim MyRange As Range 'Create range object Set MyRange = Range(“A1:A10”) 'Delete previous conditional formats MyRange.FormatConditions.Delete 'Add a Top10 condition MyRange.FormatConditions.AddTop10 With MyRange.FormatConditions(1) 'Set top to bottom parameter .TopBottom = xlTop10Top 'Set top 5 only .Rank = 5 End With With MyRange.FormatConditions(1).Font 'Set the font color .Color = -16383844 End With With MyRange.FormatConditions(1).Interior 'Set the cellbackground color .Color = 13551615 End With End Sub
The data on your worksheet would look like this after running the code:
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:
MyRange. FormatConditions(1).StopIfTrue = False
The SetFirstPriority parameter dictates whether that condition rule will be evaluated first when there are multiple rules for that cell.
MyRange. FormatConditions(1).SetFirstPriority
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:
MyRange. FormatConditions(1).Priority=3
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:
Sub ReferToAnotherCellForConditionalFormatting() 'Create variables to hold the number of rows for the tabular data Dim RRow As Long, N As Long 'Capture the number of rows within the tabular data range RRow = ActiveSheet.UsedRange.Rows.Count 'Iterate through all the rows in the tabular data range For N = 1 To RRow 'Use a Select Case statement to evaluate the formatting based on column 2 Select Case ActiveSheet.Cells(N, 2).Value 'Turn the interior color to blue Case "Blue" ActiveSheet.Cells(N, 1).Interior.Color = vbBlue 'Turn the interior color to red Case "Red" ActiveSheet.Cells(N, 1).Interior.Color = vbRed 'Turn the interior color to green Case "Green" ActiveSheet.Cells(N, 1).Interior.Color = vbGreen End Select Next N End Sub
Once this code has been run, your worksheet will now look like this:
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. |
замечания
Вы не можете определить более трех условных форматов для диапазона. Используйте метод Modify для изменения существующего условного формата или используйте метод Delete для удаления существующего формата перед добавлением нового.
FormatConditions.Add
Синтаксис:
FormatConditions.Add(Type, Operator, Formula1, Formula2)
Параметры:
название | Обязательный / необязательный | Тип данных |
---|---|---|
Тип | необходимые | XlFormatConditionType |
оператор | Необязательный | Вариант |
Формула 1 | Необязательный | Вариант |
Formula2 | Необязательный | Вариант |
XlFormatConditionType enumaration:
название | Описание |
---|---|
xlAboveAverageCondition | Выше среднего условия |
xlBlanksCondition | Состояние бланков |
xlCellValue | Значение ячейки |
xlColorScale | Цветовая гамма |
xlDatabar | Databar |
xlErrorsCondition | Условие ошибок |
xlExpression | выражение |
XlIconSet | Набор значков |
xlNoBlanksCondition | Отсутствие состояния пробелов |
xlNoErrorsCondition | Нет ошибок. |
xlTextString | Текстовая строка |
xlTimePeriod | Временной период |
xlTop10 | Топ-10 значений |
xlUniqueValues | Уникальные значения |
Форматирование по значению ячейки:
With Range("A1").FormatConditions.Add(xlCellValue, xlGreater, "=100")
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
Операторы:
название |
---|
xlBetween |
xlEqual |
xlGreater |
xlGreaterEqual |
xlLess |
xlLessEqual |
xlNotBetween |
xlNotEqual |
Если Type является выражением xlExpression, аргумент Operator игнорируется.
Форматирование по тексту содержит:
With Range("a1:a10").FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="egg")
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
Операторы:
название | Описание |
---|---|
xlBeginsWith | Начинается с указанного значения. |
xlContains | Содержит указанное значение. |
xlDoesNotContain | Не содержит указанного значения. |
xlEndsWith | Завершить указанное значение |
Форматирование по времени
With Range("a1:a10").FormatConditions.Add(xlTimePeriod, DateOperator:=xlToday)
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
Операторы:
название |
---|
xlYesterday |
xlTomorrow |
xlLast7Days |
xlLastWeek |
xlThisWeek |
xlNextWeek |
xlLastMonth |
xlThisMonth |
xlNextMonth |
Удалить условный формат
Удалите все условные форматы в диапазоне:
Range("A1:A10").FormatConditions.Delete
Удалите все условные форматы на листе:
Cells.FormatConditions.Delete
FormatConditions.AddUniqueValues
Выделение повторяющихся значений
With Range("E1:E100").FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
Выделение уникальных значений
With Range("E1:E100").FormatConditions.AddUniqueValues
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
FormatConditions.AddTop10
Выделение верхних 5 значений
With Range("E1:E100").FormatConditions.AddTop10
.TopBottom = xlTop10Top
.Rank = 5
.Percent = False
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
FormatConditions.AddAboveAverage
With Range("E1:E100").FormatConditions.AddAboveAverage
.AboveBelow = xlAboveAverage
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
Операторы:
название | Описание |
---|---|
XlAboveAverage | Выше среднего |
XlAboveStdDev | Выше стандартного отклонения |
XlBelowAverage | Ниже среднего |
XlBelowStdDev | Ниже стандартного отклонения |
XlEqualAboveAverage | Равно выше среднего |
XlEqualBelowAverage | Равновесие ниже среднего |
FormatConditions.AddIconSetCondition
Range("a1:a10").FormatConditions.AddIconSetCondition
With Selection.FormatConditions(1)
.ReverseOrder = False
.ShowIconOnly = False
.IconSet = ActiveWorkbook.IconSets(xl3Arrows)
End With
With Selection.FormatConditions(1).IconCriteria(2)
.Type = xlConditionValuePercent
.Value = 33
.Operator = 7
End With
With Selection.FormatConditions(1).IconCriteria(3)
.Type = xlConditionValuePercent
.Value = 67
.Operator = 7
End With
IconSet:
название |
---|
xl3Arrows |
xl3ArrowsGray |
xl3Flags |
xl3Signs |
xl3Stars |
xl3Symbols |
xl3Symbols2 |
xl3TrafficLights1 |
xl3TrafficLights2 |
xl3Triangles |
xl4Arrows |
xl4ArrowsGray |
xl4CRV |
xl4RedToBlack |
xl4TrafficLights |
xl5Arrows |
xl5ArrowsGray |
xl5Boxes |
xl5CRV |
xl5Quarters |
Тип:
название |
---|
xlConditionValuePercent |
xlConditionValueNumber |
xlConditionValuePercentile |
xlConditionValueFormula |
Оператор:
название | Значение |
---|---|
xlGreater | 5 |
xlGreaterEqual | 7 |
Значение:
Возвращает или устанавливает пороговое значение для значка в условном формате.
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
FormatCondition object (Excel) |
vbaxl10.chm511072 |
vbaxl10.chm511072 |
excel |
Excel.FormatCondition |
38a2bca9-9b28-3ef2-8c7a-4d35a27229ec |
07/18/2019 |
medium |
FormatCondition object (Excel)
Represents a conditional format.
Remarks
The FormatCondition object is a member of the FormatConditions collection. The FormatConditions collection can now contain more than three conditional formats for a given range.
Use the Add method of the FormatConditions object to create a new conditional format. If a range has multiple formats, you can use the Modify method to change one of the formats, or you can use the Delete method to delete a format, and then use the Add method to create a new format.
Use the Font, Borders, and Interior properties of the FormatCondition object to control the appearance of formatted cells. Some properties of these objects aren’t supported by the conditional format object model. Some of the properties that can be used with conditional formatting are listed in the following table.
Object | Properties you can use with conditional formatting |
---|---|
Font | Bold, Color, ColorIndex, FontStyle, Italic, Strikethrough, ThemeColor, ThemeFont, TintAndShade, and Underline
The accounting underline styles cannot be used. |
Borders | The following borders can be used (all others aren’t supported): xlBottom, xlLeft, xlRight, xlTop.
The following border styles can be used (all others aren’t supported): xlLineStyleNone, xlContinuous, xlDash, xlDot, xlDashDot, xlDashDotDot, xlGray50, xlGray75, and xlGray25. The following border weights can be used (all others aren’t supported): xlHairline and xlThin. |
Interior | Color, ColorIndex, Gradient, Pattern, PatternColor, PatternColorIndex, PatternThemeColor, PatternTintAndShade, ThemeColor, and TintAndShade. |
Example
Use FormatConditions (index), where index is the index number of the conditional format, to return a FormatCondition object. The following example sets format properties for an existing conditional format for cells E1:E10.
With Worksheets(1).Range("e1:e10").FormatConditions(1) With .Borders .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = 6 End With With .Font .Bold = True .ColorIndex = 3 End With End With
Methods
- Delete
- Modify
- ModifyAppliesToRange
- SetFirstPriority
- SetLastPriority
Properties
- Application
- AppliesTo
- Borders
- Creator
- DateOperator
- Font
- Formula1
- Formula2
- Interior
- NumberFormat
- Operator
- Parent
- Priority
- PTCondition
- ScopeType
- StopIfTrue
- Text
- TextOperator
- Type
See also
- Excel Object Model Reference
[!includeSupport and feedback]
We can apply conditional formattingConditional formatting is a technique in Excel that allows us to format cells in a worksheet based on certain conditions. It can be found in the styles section of the Home tab.read more to a cell or range of cells in Excel. A conditional format is a format that is applied only to cells that meet certain criteria, say values above a particular value, positive or negative values, or values with a particular formula, etc. This conditional formatting can also be done in Excel VBA programming using the ‘FormatConditions collection‘ macro/procedure.
The FormatConditions represents a conditional format that one can set by calling a method that returns a variable of that type. It contains all conditional formats for a single range and can hold only three format conditions.
Table of contents
- Conditional Formatting in Excel VBA
- Examples of VBA Conditional Formatting
- Example #1
- Example #2
- Things to Remember About VBA Conditional Formatting
- Recommended Articles
- Examples of VBA Conditional Formatting
FormatConditions.Add/Modify/Delete is used in VBA to add/modify/delete FormatCondition objects to the collection. A FormatCondition object represents each format. FormatConditions is a property of the Range object, and Add the following parameters with the below syntax:
FormatConditions.Add (Type, Operator, Formula1, Formula2)
The Add formula syntax has the following arguments:
- Type: Required. It represents the conditional format based on the value present in the cell or an expression.
- Operator: Optional. It represents the operator’s value when ‘Type’ is based on cell value.
- Formula1: Optional. It represents the value or expression associated with the conditional format.
- Formula2: Optional. It represents the value or expression associated with the second part of the conditional format when the parameter: ‘Operator’ is either ‘xlBetween’ or ‘xlNotBetween.’
FormatConditions.Modify also has the same syntax as FormatConditions.Add.
Following is the list of some values/enumerations that some parameters of ‘Add’/’Modify’ can take:
Examples of VBA Conditional Formatting
Below are examples of conditional formatting in Excel VBA.
You can download this VBA Conditional Formatting Template here – VBA Conditional Formatting Template
Example #1
We have an Excel file containing some students’ names and marks. We wish to determine/highlight the marks as “Bold” and “blue,” which are greater than 80. “Bold” and “Red,” which is less than 50. Let us see the data contained in the file:
We use the FormatConditions.Add the function below to accomplish this:
- Go to Developer -> Visual Basic Editor:
- Right-click on the workbook name in the ‘Project-VBAProject’ pane-> ‘Insert’-> ‘Module.’
- Now write the code/procedure in this module:
Code:
Sub formatting() End Sub
- Define the variable rng, condition1, condition2:
Code:
Sub formatting() Dim rng As Range Dim condition1 As FormatCondition, condition2 As FormatCondition End Sub
- Set/fix the range on which the conditional formatting needs using the VBA ‘Range’ function:
Code:
Sub formatting() Dim rng As Range Dim condition1 As FormatCondition, condition2 As FormatCondition Set rng = Range("B2", "B11") End Sub
- Delete/clear any existing conditional formatting (if any) from the range, using ‘FormatConditions.Delete’:
Code:
Sub formatting() Dim rng As Range Dim condition1 As FormatCondition, condition2 As FormatCondition Set rng = Range("B2", "B11") rng.FormatConditions.Delete End Sub
- Now, define and set the criteria for each conditional format, using ‘FormatConditions.Add’:
Code:
Sub formatting() Dim rng As Range Dim condition1 As FormatCondition, condition2 As FormatCondition Set rng = Range("B2", "B11") rng.FormatConditions.Delete Set condition1 = rng.FormatConditions.Add(xlCellValue, xlGreater, "=80") Set condition2 = rng.FormatConditions.Add(xlCellValue, xlLess, "=50") End Sub
- Define and set the format to be applied for each condition.
Copy and paste this code into your VBA class moduleUsers have the ability to construct their own VBA Objects in VBA Class Modules. The objects created in this module can be used in any VBA project.read more.
Code:
Sub formatting() 'Definining the variables: Dim rng As Range Dim condition1 As FormatCondition, condition2 As FormatCondition 'Fixing/Setting the range on which conditional formatting is to be desired Set rng = Range("B2", "B11") 'To delete/clear any existing conditional formatting from the range rng.FormatConditions.Delete 'Defining and setting the criteria for each conditional format Set condition1 = rng.FormatConditions.Add(xlCellValue, xlGreater, "=80") Set condition2 = rng.FormatConditions.Add(xlCellValue, xlLess, "=50") 'Defining and setting the format to be applied for each condition With condition1 .Font.Color = vbBlue .Font.Bold = True End With With condition2 .Font.Color = vbRed .Font.Bold = True End With End Sub
Now, when we run this code using the F5 key or manually, we see that the marks that are less than 50 get highlighted in bold and red, while those that are greater than 80 get highlighted in bold and blue as follows:
Note: Some of the properties for the appearance of formatted cells that can we can use with FormatCondition are:
Example #2
Let’s say in the above example. We have another column that states that the student is a ‘Topper’ if they score more than 80. Else, written Pass/Fail against them. Now, we wish to highlight the values stated as ‘Topper’ as “Bold” and “Blue.” Let us see the data contained in the file:
In this case, the code/procedure would work as follows:
Code:
Sub TextFormatting() End Sub
Define and set the format to be applied for each condition
Code:
Sub TextFormatting() With Range("c2:c11").FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="topper") With .Font .Bold = True .Color = vbBlue End With End With End Sub
We can see in the above code that we wish to test if the range: ‘C2:C11″ contains the string: “Topper,” so the parameter: “Onamestor” of ‘Format.Add’ takes the enumeration:” Xcontains” to test this condition in the fixed range (i.e., C2:C11). Then, do the required conditional formatting (font changes) on this range.
Now when we run this code manually or by pressing the F5 key, we see that cell values with ‘Topper’ get highlighted in blue and bold:
Note: In the above two examples, we have seen how the ‘Add’ method works in case of any cell value criteria (numeric or text string).
Below are some other instances/criteria that we can use to test and thus apply VBA conditional formatting:
- Format by Time Period
- Average condition
- Colour Scale condition
- IconSet condition
- Databar condition
- Unique Values
- Duplicate Values
- Top10 values
- Percentile Condition
- Blanks Condition, etc.
With different conditions to test, different values/enumerations taken by parameters of ‘Add.’
Things to Remember About VBA Conditional Formatting
- We can use the ‘Add’ method with ‘FormatConditions’ to create a new conditional format, the ‘Delete’ method to delete any conditional format, and the ‘Modify’ method to alter any existing conditional format.
- The ‘Add’ method with ‘FormatConditions Collection’ fails if we create more than three conditional formats for a single range.
- To apply more than three conditional formats to a range using the ‘Add’ method, we can use ‘If’ or ‘select case.’
- If the ‘Add’ method has its ‘Type’ parameter as: ‘xlExpression,’ then the parameter ‘Operator’ is ignored.
- The parameters: ‘Formula1’ and ‘Formula2’ in the ‘Add’ method can be a cell reference, constant value, string value, or even a formula.
- The parameter: ‘Formula2’ is used only when the parameter: ‘Operator’ is either ‘xlBetween’ or ‘xlNotBetween,’ or else it is ignored.
- To remove all the conditional formatting from any worksheet, we can use the ‘Delete’ method as follows:
Cells.FormatConditions.Delete
Recommended Articles
This article has been a guide to VBA Conditional Formatting. Here, we learn how to apply conditional formatting to an Excel cell using the Format Conditions method in VBA, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –
- VBA Wait Function
- VBA TimeValue
- Using Formulas with Conditional Formatting
- Conditional Formatting for Blank Cells
# FormatConditions.Add
# Syntax:
# Parameters:
Name | Required / Optional | Data Type |
---|---|---|
Type | Required | XlFormatConditionType |
Operator | Optional | Variant |
Formula1 | Optional | Variant |
Formula2 | Optional | Variant |
# XlFormatConditionType enumaration:
Name | Description |
---|---|
xlAboveAverageCondition | Above average condition |
xlBlanksCondition | Blanks condition |
xlCellValue | Cell value |
xlColorScale | Color scale |
xlDatabar | Databar |
xlErrorsCondition | Errors condition |
xlExpression | Expression |
XlIconSet | Icon set |
xlNoBlanksCondition | No blanks condition |
xlNoErrorsCondition | No errors condition |
xlTextString | Text string |
xlTimePeriod | Time period |
xlTop10 | Top 10 values |
xlUniqueValues | Unique values |
# Formatting by cell value:
# Operators:
Name |
---|
xlBetween |
xlEqual |
xlGreater |
xlGreaterEqual |
xlLess |
xlLessEqual |
xlNotBetween |
xlNotEqual |
If Type is xlExpression, the Operator argument is ignored.
# Formatting by text contains:
# Operators:
Name | Description |
---|---|
xlBeginsWith | Begins with a specified value. |
xlContains | Contains a specified value. |
xlDoesNotContain | Does not contain the specified value. |
xlEndsWith | Endswith the specified value |
# Formatting by time period
# Operators:
Name |
---|
xlYesterday |
xlTomorrow |
xlLast7Days |
xlLastWeek |
xlThisWeek |
xlNextWeek |
xlLastMonth |
xlThisMonth |
xlNextMonth |
# Remove conditional format
# Remove all conditional format in range:
# Remove all conditional format in worksheet:
# FormatConditions.AddUniqueValues
# Highlighting Duplicate Values
# Highlighting Unique Values
# FormatConditions.AddTop10
# Highlighting Top 5 Values
# FormatConditions.AddAboveAverage
# Operators:
Name | Description |
---|---|
XlAboveAverage | Above average |
XlAboveStdDev | Above standard deviation |
XlBelowAverage | Below average |
XlBelowStdDev | Below standard deviation |
XlEqualAboveAverage | Equal above average |
XlEqualBelowAverage | Equal below average |
# FormatConditions.AddIconSetCondition
(opens new window)
# IconSet:
Name |
---|
xl3Arrows |
xl3ArrowsGray |
xl3Flags |
xl3Signs |
xl3Stars |
xl3Symbols |
xl3Symbols2 |
xl3TrafficLights1 |
xl3TrafficLights2 |
xl3Triangles |
xl4Arrows |
xl4ArrowsGray |
xl4CRV |
xl4RedToBlack |
xl4TrafficLights |
xl5Arrows |
xl5ArrowsGray |
xl5Boxes |
xl5CRV |
xl5Quarters |
(opens new window)
# Type:
Name |
---|
xlConditionValuePercent |
xlConditionValueNumber |
xlConditionValuePercentile |
xlConditionValueFormula |
# Operator:
Name | Value |
---|---|
xlGreater | 5 |
xlGreaterEqual | 7 |
# Value:
Returns or sets the threshold value for an icon in a conditional format.
You cannot define more than three conditional formats for a range. Use the Modify method to modify an existing conditional format, or use the Delete method to delete an existing format before adding a new one.
FormatCondition Object
Represents a conditional format. The FormatCondition object is a member of the FormatConditions collection. The FormatConditions collection can contain up to three conditional formats for a given range.
Using the FormatCondition Object
Use FormatConditions(index), where index is the index number of the conditional format, to return a FormatCondition object. The following example sets format properties for an existing conditional format for cells E1:E10.
With Worksheets(1).Range("e1:e10").FormatConditions(1)
With .Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = 6
End With
With .Font
.Bold = True
.ColorIndex = 3
End With
End With
Remarks
Use the Add method to create a new conditional format. If you try to create more than three conditional formats for a single range, the Add method fails. If a range has three formats, you can use the Modify method to change one of the formats, or you can use the Delete method to delete a format and then use the Add method to create a new format.
Use the Font, Border, and Interior properties of the FormatCondition object to control the appearance of formatted cells. Some properties of these objects aren’t supported by the conditional format object model. The properties that can be used with conditional formatting are listed in the following table.
Object | Properties |
---|---|
Font | Bold
Color ColorIndex FontStyle Italic Strikethrough Underline The accounting underline styles cannot be used. |
Border | Bottom
Color Left Right Style The following border styles can be used (all others aren’t supported): xlNone, xlSolid, xlDash, xlDot, xlDashDot, xlDashDotDot, xlGray50, xlGray75, and xlGray25. Top Weight The following border weights can be used (all others aren’t supported): xlWeightHairline and xlWeightThin. |
Interior | Color
ColorIndex Pattern PatternColorIndex |