Excel conditional formatting format

Conditional formatting can help make patterns and trends in your data more apparent. To use it, you create rules that determine the format of cells based on their values, such as the following monthly temperature data with cell colors tied to cell values. 

Conditional formatting example

You can apply conditional formatting to a range of cells (either a selection or a named range), an Excel table, and in Excel for Windows, even a PivotTable report.

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

Conditional formatting typically works the same way in a range of cells, an Excel table, or a PivotTable report. However, conditional formatting in a PivotTable report has some extra considerations:

  • There are some conditional formats that don’t work with fields in the Values area of a PivotTable report. For example, you can’t format such fields based on whether they contain unique or duplicate values. These restrictions are mentioned in the remaining sections of this article, where applicable.

  • If you change the layout of the PivotTable report by filtering, hiding levels, collapsing and expanding levels, or moving a field, the conditional format is maintained as long as the fields in the underlying data are not removed.

  • The scope of the conditional format for fields in the Values area can be based on the data hierarchy and is determined by all the visible children (the next lower level in a hierarchy) of a parent (the next higher level in a hierarchy) on rows for one or more columns, or columns for one or more rows.

    Note: In the data hierarchy, children do not inherit conditional formatting from the parent, and the parent does not inherit conditional formatting from the children.

  • There are three methods for scoping the conditional format of fields in the Values area: by selection, by corresponding field, and by value field.

The default method of scoping fields in the Values area is by selection. You can change the scoping method to the corresponding field or value field by using the Apply formatting rule to option button, the New Formatting Rule dialog box, or the Edit Formatting Rule dialog box.

Method

Use this method if you want to select

Scoping by selection

  • A contiguous set of fields in the Values area, such as all of the product totals for one region.

  • A non-contiguous set of fields in the Values area, such as product totals for different regions across levels in the data hierarchy.

Scoping by value field

  • Avoid making many non-contiguous selections.

  • Conditionally format a set of fields in the Values area for all levels in the hierarchy of data.

  • Include subtotals and grand totals.

Scoping by corresponding field

  • Avoid making many non-contiguous selections.

  • Conditionally format a set of fields in the Values area for one level in the hierarchy of data.

  • Exclude subtotals.

When you conditionally format fields in the Values area for top, bottom, above average, or below average values, the rule is based on all visible values by default. However, when you scope by corresponding field, instead of using all visible values, you can apply the conditional format for each combination of:

  • A column and its parent row field.

  • A row and its parent column field.

Note: Quick Analysis is not available in Excel 2010 and previous versions.

Use the Quick Analysis button Quick Analysis button to apply selected conditional formatting to the selected data. The Quick Analysis button appears automatically when you select data.

  1. Select the data that you want to conditionally format. The Quick Analysis button appears on the lower-right corner of the selection.

    Selected data with the Quick Analysis button

  2. Click the Quick Analysis button Quick Analysis button, or press Ctrl+Q.

  3. In the pop-up that appears, on the Formatting tab, move your mouse over the different options to see a Live Preview on your data, and then click on the formatting option you want.

    Formatting tab in the Quick Analysis gallery

    Notes: 

    • The formatting options that appear in the Formatting tab depend on the data you have selected. If your selection contains only text, then the available options are Text, Duplicate, Unique, Equal To, and Clear. When the selection contains only numbers, or both text and numbers, then the options are Data Bars, Colors, Icon Sets, Greater, Top 10%, and Clear.

    • Live preview will only render for those formatting options that can be used on your data. For example, if your selected cells don’t contain matching data and you select Duplicate, the live preview will not work.

  4. If the Text that Contains dialog box appears, enter the formatting option you want to apply and click OK.

If you’d like to watch a video that shows how to use Quick Analysis to apply conditional formatting, see Video: Use conditional formatting.

You can download a sample workbook that contains different examples of applying conditional formatting, both with standard rules such as top and bottom, duplicates, Data Bars, Icon Sets and Color Scales, as well as manually creating rules of your own.

Download: Conditional formatting examples in Excel

Color scales are visual guides that help you understand data distribution and variation. A two-color scale helps you compare a range of cells by using a gradation of two colors. The shade of the color represents higher or lower values. For example, in a green and yellow color scale, as shown below, you can specify that higher value cells have a more green color and lower value cells have a more yellow color.

Tip: You can sort cells that have this format by their color — just use the context menu.

Formatting all cells with a two-color scale

Tip: If any cells in the selection contain a formula that returns an error, the conditional formatting is not applied to those cells. To ensure that the conditional formatting is applied to those cells, use an IS or IFERROR function to return a value other than an error value.

Quick formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Color Scales.

    Conditional Formatting

  3. Select a two-color scale.

    Hover over the color scale icons to see which icon is a two-color scale. The top color represents higher values, and the bottom color represents lower values.

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Formatting Options button that appears next to a PivotTable field that has conditional formatting applied.

Advanced formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a completely new conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report by:

    • Selection: Click Selected cells.

    • All cells for a Value label: Click All cells showing <Value label> values.

    • All cells for a Value label, excluding subtotals and the grand total: Click All cells showing <Value label> values for <Row Label>.

  5. Under Select a Rule Type, click Format all cells based on their values (default).

  6. Under Edit the Rule Description, in the Format Style list box, select 2-Color Scale.

  7. To select a type in the Type box for Minimum and Maximum, do one of the following:

    • Format lowest and highest values:    Select Lowest Value and Highest Value.

      In this case, you do not enter a Minimum and MaximumValue.

    • Format a number, date, or time value:    Select Number and then enter a Minimum and MaximumValue.

    • Format a percentage Percent:    Enter a Minimum and MaximumValue.

      Valid values are from 0 (zero) to 100. Don’t enter a percent sign.

      Use a percentage when you want to visualize all values proportionally because the distribution of values is proportional.

    • Format a percentile:    Select Percentile and then enter a Minimum and MaximumValue. Valid percentiles are from 0 (zero) to 100.

      Use a percentile when you want to visualize a group of high values (such as the top 20thpercentile) in one color grade proportion and low values (such as the bottom 20th percentile) in another color grade proportion, because they represent extreme values that might skew the visualization of your data.

    • Format a formula result:    Select Formula and then enter values for Minimum and Maximum.

      • The formula must return a number, date, or time value.

      • Start the formula with an equal sign (=).

      • Invalid formulas result in no formatting being applied.

      • It’s a good idea to test the formula to make sure that it doesn’t return an error value.

        Notes: 

        • Make sure that the Minimum value is less than the Maximum value.

        • You can choose a different type for the Minimum and Maximum. For example, you can choose a number for Minimum a percentage for Maximum.

  8. To choose a Minimum and Maximum color scale, click Color for each, and then select a color.

    If you want to choose additional colors or create a custom color, click More Colors. The color scale you select is shown in the Preview box.

Color scales are visual guides that help you understand data distribution and variation. A three-color scale helps you compare a range of cells by using a gradation of three colors. The shade of the color represents higher, middle, or lower values. For example, in a green, yellow, and red color scale, you can specify that higher value cells have a green color, middle value cells have a yellow color, and lower value cells have a red color.

Tip: You can sort cells that have this format by their color — just use the context menu.

Quick formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Color Scales.

    Conditional Formatting

  3. Select a three-color scale. The top color represents higher values, the center color represents middle values, and the bottom color represents lower values.

    Hover over the color scale icons to see which icon is a three-color scale.

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Formatting Options button that appears next to a PivotTable field that has conditional formatting applied..

Advanced formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a new conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report by:

    • Selection:    Click Just these cells.

    • Corresponding field:    Click All <value field> cells with the same fields.

    • Value field:    Click All <value field> cells.

  5. Under Select a Rule Type, click Format all cells based on their values.

  6. Under Edit the Rule Description, in the Format Style list box, select 3-Color Scale.

  7. Select a type for Minimum, Midpoint, and Maximum. Do one of the following:

    • Format lowest and highest values:    Select a Midpoint.

      In this case, you do not enter a Lowest and HighestValue.

    • Format a number, date, or time value:    Select Number and then enter a value for Minimum, Midpoint, and Maximum.

    • Format a percentage:    Select Percent and then enter a value for Minimum, Midpoint, and Maximum. Valid values are from 0 (zero) to 100. Do not enter a percent (%) sign.

      Use a percentage when you want to visualize all values proportionally, because using a percentage ensures that the distribution of values is proportional.

    • Format a percentile:    Select Percentile and then enter a value for Minimum, Midpoint, and Maximum.

      Valid percentiles are from 0 (zero) to 100.

      Use a percentile when you want to visualize a group of high values (such as the top 20th percentile) in one color grade proportion and low values (such as the bottom 20th percentile) in another color grade proportion, because they represent extreme values that might skew the visualization of your data.

    • Format a formula result:    Select Formula and then enter a value for Minimum, Midpoint, and Maximum.

      The formula must return a number, date, or time value. Start the formula with an equal sign (=). Invalid formulas result in no formatting being applied. It’s a good idea to test the formula to make sure that it doesn’t return an error value.

      Notes: 

      • You can set minimum, midpoint, and maximum values for the range of cells. Make sure that the value in Minimum is less than the value in Midpoint, which in turn is less than the value in Maximum.

      • You can choose a different type for Minimum, Midpoint, and Maximum. For example, you can choose a Minimum number, Midpoint percentile, and Maximum percent.

      • In many cases, the default Midpoint value of 50 percent works best, but you can adjust this to fit unique requirements.

  8. To choose a Minimum, Midpoint, and Maximum color scale, click Color for each, and then select a color.

    • To choose additional colors or create a custom color, click More Colors.

    • The color scale you select is shown in the Preview box.

A data bar helps you see the value of a cell relative to other cells. The length of the data bar represents the value in the cell. A longer bar represents a higher value, and a shorter bar represents a lower value. Data bars are useful in spotting higher and lower numbers, especially with large amounts of data, such as top selling and bottom selling toys in a holiday sales report.

The example shown here uses data bars to highlight dramatic positive and negative values. You can format data bars so that the data bar starts in the middle of the cell, and stretches to the left for negative values.

Data bars that highlight positive and negative values

Tip: If any cells in the range contain a formula that returns an error, the conditional formatting is not applied to those cells. To ensure that the conditional formatting is applied to those cells, use an IS or IFERROR function to return a value (such as 0 or «N/A») instead of an error value.

Quick formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Style group, click the arrow next to Conditional Formatting, click Data Bars, and then select a data bar icon.

    Conditional Formatting

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Apply formatting rule to option button.

Advanced formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report by:

    • Selection:    Click Just these cells.

    • Corresponding field:    Click All <value field> cells with the same fields.

    • Value field:    Click All <value field> cells.

  5. Under Select a Rule Type, click Format all cells based on their values.

  6. Under Edit the Rule Description, in the Format Style list box, select Data Bar.

  7. Select a Minimum and MaximumType. Do one of the following:

    • Format lowest and highest values:    Select Lowest Value and Highest Value.

      In this case, you do not enter a value for Minimum and Maximum.

    • Format a number, date, or time value:    Select Number and then enter a Minimum and MaximumValue.

    • Format a percentage:    Select Percent and then enter a value for Minimum and Maximum.

      Valid values are from 0 (zero) to 100. Do not enter a percent (%) sign.

      Use a percentage when you want to visualize all values proportionally, because using a percentage ensures that the distribution of values is proportional.

    • Format a percentile    Select Percentile and then enter a value for Minimum and Maximum.

      Valid percentiles are from 0 (zero) to 100.

      Use a percentile when you want to visualize a group of high values (such as the top 20th percentile) in one data bar proportion and low values (such as the bottom 20th percentile) in another data bar proportion, because they represent extreme values that might skew the visualization of your data.

    • Format a formula result     Select Formula, and then enter a value for Minimum and Maximum.

      • The formula has to return a number, date, or time value.

      • Start the formula with an equal sign (=).

      • Invalid formulas result in no formatting being applied.

      • It’s a good idea to test the formula to make sure that it doesn’t return an error value.

    Notes: 

    • Make sure that the Minimum value is less than the Maximum value.

    • You can choose a different type for Minimum and Maximum. For example, you can choose a Minimum number and a Maximum percent.

  8. To choose a Minimum and Maximum color scale, click Bar Color.

    If you want to choose additional colors or create a custom color, click More Colors. The bar color you select is shown in the Preview box.

  9. To show only the data bar and not the value in the cell, select Show Bar Only.

  10. To apply a solid border to data bars, select Solid Border in the Border list box and choose a color for the border.

  11. To choose between a solid bar and a gradiated bar, choose Solid Fill or Gradient Fill in the Fill list box.

  12. To format negative bars, click Negative Value and Axis and then, in the Negative Value and Axis Settings dialog box, choose options for the negative bar fill and border colors. You can choose position settings and a color for the axis. When you are finished selecting options, click OK.

  13. You can change the direction of bars by choosing a setting in the Bar Direction list box. This is set to Context by default, but you can choose between a left-to-right and a right-to-left direction, depending on how you want to present your data.

Use an icon set to annotate and classify data into three to five categories separated by a threshold value. Each icon represents a range of values. For example, in the 3 Arrows icon set, the green up arrow represents higher values, the yellow sideways arrow represents middle values, and the red down arrow represents lower values.

Tip: You can sort cells that have this format by their icon — just use the context menu.

The example shown here works with several examples of conditional formatting icon sets.

Different icon sets for the same data

You can choose to show icons only for cells that meet a condition; for example, displaying a warning icon for those cells that fall below a critical value and no icons for those that exceed it. To do this, you hide icons by selecting No Cell Icon from the icon drop-down list next to the icon when you are setting conditions. You can also create your own combination of icon sets; for example, a green «symbol» check mark, a yellow «traffic light», and a red «flag.»

Tip: If any cells in the selection contain a formula that returns an error, the conditional formatting is not applied to those cells. To ensure that the conditional formatting is applied to those cells, use an IS or IFERROR function to return a value (such as 0 or «N/A») instead of an error value.

Quick formatting

  1. Select the cells that you want to conditionally format.

  2. On the Home tab, in the Style group, click the arrow next to Conditional Formatting, click Icon Set, and then select an icon set.

    Conditional Formatting

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Apply formatting rule to option button.

Advanced formatting

  1. Select the cells that you want to conditionally format.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report by:

    • Selection:    Click Just these cells.

    • Corresponding field:    Click All <value field> cells with the same fields.

    • Value field:    Click All <value field> cells.

  5. Under Select a Rule Type, click Format all cells based on their values.

  6. Under Edit the Rule Description, in the Format Style list box, select Icon Set.

    1. Select an icon set. The default is 3 Traffic Lights (Unrimmed). The number of icons and the default comparison operators and threshold values for each icon can vary for each icon set.

    2. You can adjust the comparison operators and threshold values. The default range of values for each icon are equal in size, but you can adjust these to fit your unique requirements. Make sure that the thresholds are in a logical sequence of highest to lowest from top to bottom.

    3. Do one of the following:

      • Format a number, date, or time value:    Select Number.

      • Format a percentage:    Select Percent.

        Valid values are from 0 (zero) to 100. Do not enter a percent (%) sign.

        Use a percentage when you want to visualize all values proportionally, because using a percentage ensures that the distribution of values is proportional.

      • Format a percentile:    Select Percentile. Valid percentiles are from 0 (zero) to 100.

        Use a percentile when you want to visualize a group of high values (such as the top 20th percentile) using a particular icon and low values (such as the bottom 20th percentile) using another icon, because they represent extreme values that might skew the visualization of your data.

      • Format a formula result:    Select Formula, and then enter a formula in each Value box.

        • The formula must return a number, date, or time value.

        • Start the formula with an equal sign (=).

        • Invalid formulas result in no formatting being applied.

        • It’s a good idea to test the formula to make sure that it doesn’t return an error value.

    4. To make the first icon represent lower values and the last icon represent higher values, select Reverse Icon Order.

    5. To show only the icon and not the value in the cell, select Show Icon Only.

      Notes: 

      • You may need to adjust the column width to accommodate the icon.

      • The size of the icon shown depends on the font size that is used in that cell. As the size of the font is increased, the size of the icon increases proportionally.

To more easily find specific cells, you can format them by using a comparison operator. For example, in an inventory worksheet sorted by categories, you could highlight products with fewer than 10 items on hand in yellow. Or, in a retail store summary worksheet, you might identify all stores with profits greater than 10%, sales volumes less than $100,000, and region equal to «SouthEast.»

The examples shown here work with examples of built-in conditional formatting criteria, such as Greater Than, and Top %. This formats cities with a population greater than 2,000,000 with a green background and average high temperatures in the top 30% with orange.

Formatting shows cities with more than 2 million, and top 30% of high temperatures

Note: You cannot conditionally format fields in the Values area of a PivotTable report by text or by date, only by number.

Quick formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Style group, click the arrow next to Conditional Formatting, and then click Highlight Cells Rules.

    Conditional Formatting

  3. Select the command you want, such as Between, Equal To Text that Contains, or A Date Occurring.

  4. Enter the values you want to use, and then select a format.

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Apply formatting rule to option button.

If you’d like to watch videos of these techniques, see Video: Conditionally format text and Video: Conditionally format dates.

Advanced formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet or on other worksheets, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report by:

    • Selection:    Click Just these cells.

    • Corresponding field:    Click All <value field> cells with the same fields.

    • Value field:    Click All <value field> cells.

  5. Under Select a Rule Type, click Format only cells that contain.

  6. Under Edit the Rule Description, in the Format only cells with list box, do one of the following:

    • Format by number, date, or time:    Select Cell Value, select a comparison operator, and then enter a number, date, or time.

      For example, select Between and then enter 100 and 200, or select Equal to and then enter 1/1/2009.

      You can also enter a formula that returns a number, date, or time value.

      • If you enter a formula, start it with an equal sign (=).

      • Invalid formulas result in no formatting being applied.

      • It’s a good idea to test the formula to make sure that it doesn’t return an error value.

    • Format by text:    Select Specific Text, choosing a comparison operator, and then enter text.

      For example, select Contains and then enter Silver, or select Starting with and then enter Tri.

      Quotes are included in the search string, and you may use wildcard characters. The maximum length of a string is 255 characters.

      You can also enter a formula that returns text.

      • If you enter a formula, start it with an equal sign (=).

      • Invalid formulas result in no formatting being applied.

      • It’s a good idea to test the formula to make sure that it doesn’t return an error value.

      To see a video of this technique, see Video: Conditionally format text.

    • Format by date:    Select Dates Occurring and then select a date comparison.

      For example, select Yesterday or Next week.

      To see a video of this technique, see Video: Conditionally format dates.

    • Format cells with blanks or no blanks:    Select Blanks or No Blanks.

      A blank value is a cell that contains no data and is different from a cell that contains one or more spaces (spaces are considered as text).

    • Format cells with error or no error values:    Select Errors or No Errors.

      Error values include: #####, #VALUE!, #DIV/0!, #NAME?, #N/A, #REF!, #NUM!, and #NULL!.

  7. To specify a format, click Format. The Format Cells dialog box appears.

  8. Select the number, font, border, or fill format you want to apply when the cell value meets the condition, and then click OK.

    You can choose more than one format. The formats you select are shown in the Preview box.

You can find the highest and lowest values in a range of cells that are based on a cutoff value you specify. For example, you can find the top 5 selling products in a regional report, the bottom 15% products in a customer survey, or the top 25 salaries in a department .

Quick formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Style group, click the arrow next to Conditional Formatting, and then click Top/Bottom Rules.

    Conditional Formatting

  3. Select the command you want, such as Top 10 items or Bottom 10 %.

  4. Enter the values you want to use, and then select a format.

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Apply formatting rule to option button.

Advanced formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope fields in the Values area of a PivotTable report by:

    • Selection:    Click Just these cells.

    • Corresponding field:    Click All <value field> cells with the same fields.

    • Value field:    Click All <value field> cells.

  5. Under Select a Rule Type, click Format only top or bottom ranked values.

  6. Under Edit the Rule Description, in the Format values that rank in the list box, select Top or Bottom.

  7. Do one of the following:

    • To specify a top or bottom number, enter a number and then clear the % of the selected range box. Valid values are 1 to 1000.

    • To specify a top or bottom percentage, enter a number and then select the % of the selected range box. Valid values are 1 to 100.

  8. Optionally, change how the format is applied for fields in the Values area of a PivotTable report that are scoped by corresponding field.

    By default, the conditional format is based on all visible values. However when you scope by corresponding field, instead of using all visible values, you can apply the conditional format for each combination of:

    • A column and its parent row field, by selecting each Column group.

    • A row and its parent column field, by selecting each Row group.

  9. To specify a format, click Format. The Format Cells dialog box appears.

  10. Select the number, font, border, or fill format you want to apply when the cell value meets the condition, and then click OK.

    You can choose more than one format. The formats you select are shown in the Preview box.

You can find values above or below an average or standard deviation in a range of cells. For example, you can find the above average performers in an annual performance review or you can locate manufactured materials that fall below two standard deviations in a quality rating.

Quick formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Style group, click the arrow next to Conditional Formatting, and then click Top/Bottom Rules.

    Conditional Formatting

  3. Select the command you want, such as Above Average or Below Average.

  4. Enter the values you want to use, and then select a format.

You can change the method of scoping for fields in the Values area of a PivotTable report by using the Apply formatting rule to option button.

Advanced formatting

  1. Select one or more cells in a range, table, or PivotTable report.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report by:

    • Selection:    Click Just these cells.

    • Corresponding field:    Click All <value field> cells with the same fields.

    • Value field:    Click All <value field> cells.

  5. Under Select a Rule Type, click Format only values that are above or below average.

  6. Under Edit the Rule Description, in the Format values that are list box, do one of the following:

    • To format cells that are above or below the average for all of the cells in the range, select Above or Below.

    • To format cells that are above or below one, two, or three standard deviations for all of the cells in the range, select a standard deviation.

  7. Optionally, change how the format is applied for fields in the Values area of a PivotTable report that are scoped by corresponding field.

    By default, the conditionally format is based on all visible values. However when you scope by corresponding field, instead of using all visible values, you can apply the conditional format for each combination of:

    • A column and its parent row field, by selecting each Column group.

    • A row and its parent column field, by selecting each Row group.

  8. Click Format to display the Format Cells dialog box.

  9. Select the number, font, border, or fill format you want to apply when the cell value meets the condition, and then click OK.

    You can choose more than one format. The formats you select are displayed in the Preview box.

Note: You can’t conditionally format fields in the Values area of a PivotTable report by unique or duplicate values.

In the example shown here, conditional formatting is used on the Instructor column to find instructors that are teaching more than one class (duplicate instructor names are highlighted in a pale red color). Grade values that are found just once in the Grade column (unique values) are highlighted in a green color.

Values in column C that aren't unique are colored rose, unique values in column D are green

Quick formatting

  1. Select the cells that you want to conditionally format.

  2. On the Home tab, in the Style group, click the arrow next to Conditional Formatting, and then click Highlight Cells Rules.

    Conditional Formatting

  3. Select Duplicate Values.

  4. Enter the values you want to use, and then select a format.

Advanced formatting

  1. Select the cells that you want to conditionally format.

  2. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules. The Conditional Formatting Rules Manager dialog box appears.

  3. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet or table is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet, and then by selecting Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  4. Under Select a Rule Type, click Format only unique or duplicate values.

  5. Under Edit the Rule Description, in the Format all list box, select unique or duplicate.

  6. Click Format to display the Format Cells dialog box.

  7. Select the number, font, border, or fill format you want to apply when the cell value meets the condition, and then click OK.

    You can choose more than one format. The formats you select are shown in the Preview box.

If none of the above options is what you’re looking for, you can create your own conditional formatting rule in a few simple steps. 

Notes: If there’s already a rule defined that you just want to work a bit differently, duplicate the rule and edit it.

  1. Select Home > Conditional Formatting > Manage Rules, then in the Conditional Formatting Rule Manager dialog, select a listed rule and then select Duplicate Rule. The duplicate rule then appears in the list.

  2. Select the duplicate rule, then select Edit Rule.

  1. Select the cells that you want to format.

  2. On the Home tab, click Conditional Formatting > New Rule.

    New formatting rule

  3. Create your rule and specify its format options, then click OK.

    If you don’t see the options that you want, you can use a formula to determine which cells to format — see the next section for steps).

If you don’t see the exact options you need when you create your own conditional formatting rule, you can use a logical formula to specify the formatting criteria. For example, you may want to compare values in a selection to a result returned by a function or evaluate data in cells outside the selected range, which can be in another worksheet in the same workbook. Your formula must return True or False (1 or 0), but you can use conditional logic to string together a set of corresponding conditional formats, such as different colors for each of a small set of text values (for example, product category names).

Note: You can enter cell references in a formula by selecting cells directly on a worksheet or other worksheets. Selecting cells on the worksheet inserts absolute cell references. If you want Excel to adjust the references for each cell in the selected range, use relative cell references. For more information, see Create or change a cell reference and Switch between relative, absolute, and mixed references.

Tip: If any cells contain a formula that returns an error, conditional formatting is not applied to those cells. To address this, use IS functions or an IFERROR function in your formula to return a value that you specify (such as 0, or «N/A») instead of an error value.

  1. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules.

    Conditional Formatting

    The Conditional Formatting Rules Manager dialog box appears.

  2. Do one of the following:

    • To add a conditional format, click New Rule. The New Formatting Rule dialog box appears.

    • To add a new conditional format based on one that is already listed, select the rule, then click Duplicate Rule. The duplicate rule is copied and appears in the dialog box. Select the duplicate, then select Edit Rule. The Edit Formatting Rule dialog box appears. 

    • To change a conditional format, do the following:

      1. Make sure that the appropriate worksheet, table, or PivotTable report is selected in the Show formatting rules for list box.

      2. Optionally, change the range of cells by clicking Collapse Dialog in the Applies to box to temporarily hide the dialog box, by selecting the new range of cells on the worksheet or other worksheets, and then by clicking Expand Dialog.

      3. Select the rule, and then click Edit rule. The Edit Formatting Rule dialog box appears.

  3. Under Apply Rule To, to optionally change the scope for fields in the Values area of a PivotTable report, do the following:

    • To scope by selection:    Click Selected cells.

    • To scope by corresponding field:    Click All cells showing <Values field> values.

    • To scope by Value field:    Click All cells showing <Values field> for <Row>.

  4. Under Select a Rule Type, click Use a formula to determine which cells to format.

    1. Under Edit the Rule Description, in the Format values where this formula is true list box, enter a formula.

      You have to start the formula with an equal sign (=), and the formula must return a logical value of TRUE (1) or FALSE (0).

    2. Click Format to display the Format Cells dialog box.

    3. Select the number, font, border, or fill format you want to apply when the cell value meets the condition, and then click OK.

      You can choose more than one format. The formats you select are shown in the Preview box.

      Example 1: Use two conditional formats with criteria that uses AND and OR tests    

      The following example shows the use of two conditional formatting rules. If the first rule doesn’t apply, the second rule applies.

      First rule: a home buyer has budgeted up to $75,000 as a down payment and $1,500 per month as a mortgage payment. If both the down payment and the monthly payments fit these requirements, cells B4 and B5 are formatted green.

      Second rule: if either the down payment or the monthly payment doesn’t meet the buyer’s budget, B4 and B5 are formatted red. Change some values, such as the APR, the loan term, the down payment, and the purchase amount to see what happens with the conditionally formatted cells.

      Formula for first rule (applies green color)

      =AND(IF($B$4<=75000,1),IF(ABS($B$5)<=1500,1))

      Formula for second rule (applies red color)

      =OR(IF($B$4>=75000,1),IF(ABS($B$5)>=1500,1))

      Cells B4 and B5 meet their conditions, so they're formatted green

      Example 2: Shade every other row by using the MOD and ROW functions    

      A conditional format applied to every cell in this worksheet shades every other row in the range of cells with a blue cell color. You can select all cells in a worksheet by clicking the square above row 1 and to the left of column A. The MOD function returns a remainder after a number (the first argument) is divided by divisor (the second argument). The ROW function returns the current row number. When you divide the current row number by 2, you always get either a 0 remainder for an even number or a 1 remainder for an odd number. Because 0 is FALSE and 1 is TRUE, every odd numbered row is formatted. The rule uses this formula: =MOD(ROW(),2)=1.

      Every other row is shaded blue

      Note: You can enter cell references in a formula by selecting cells directly on a worksheet or other worksheets. Selecting cells on the worksheet inserts absolute cell references. If you want Excel to adjust the references for each cell in the selected range, use relative cell references. For more information, see Create or change a cell reference and Switch between relative, absolute, and mixed references.

The following video shows you the basics of using formulas with conditional formatting.

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

If you want to apply an existing formatting style to new or other data on your worksheet, you can use Format Painter to copy the conditional formatting to that data.

  1. Click the cell that has the conditional formatting that you want to copy.

  2. Click Home > Format Painter.

    Copy and Paste buttons on the Home tab

    The pointer changes to a paintbrush.

    Tip: You can double-click Format Painter if you want to keep using the paintbrush to paste the conditional formatting in other cells.

  3. To paste the conditional formatting, drag the paintbrush across the cells or ranges of cells you want to format.

  4. To stop using the paintbrush, press Esc.

Note: If you’ve used a formula in the rule that applies the conditional formatting, you might have to adjust any cell references in the formula after pasting the conditional format. For more information, see Switch between relative, absolute, and mixed references.

If your worksheet contains conditional formatting, you can quickly locate the cells so that you can copy, change, or delete the conditional formats. Use the Go To Special command to find only cells with a specific conditional format, or to find all cells that have conditional formats.

Find all cells that have a conditional format

  1. Click any cell that does not have a conditional format.

  2. On the Home tab, in the Editing group, click the arrow next to Find & Select, and then click Conditional Formatting.

    Editing group on the Home tab

Find only cells that have the same conditional format

  1. Click any cell that has the conditional format that you want to find.

  2. On the Home tab, in the Editing group, click the arrow next to Find & Select, and then click Go To Special.

  3. Click Conditional formats.

  4. Click Same under Data validation.

    Editing group on the Home tab

When you use conditional formatting, you set up rules that Excel uses to determine when to apply the conditional formatting. To manage these rules, you should understand the order in which these rules are evaluated, what happens when two or more rules conflict, how copying and pasting can affect rule evaluation, how to change the order in which rules are evaluated, and when to stop rule evaluation.

  • Learn about conditional formatting rule precedence

    You create, edit, delete, and view all conditional formatting rules in the workbook by using the Conditional Formatting Rules Manager dialog box. (On the Home tab, click Conditional Formatting, and then click Manage Rules.)

    Conditional Formatting menu with Manage Rules highlighted

    The Conditional Formatting Rules Manager dialog box appears.

    When two or more conditional formatting rules apply, these rules are evaluated in order of precedence (top to bottom) by how they are listed in this dialog box.

    Here’s an example that has expiration dates for ID badges. We want to mark badges that expire within 60 days but are not yet expired with a yellow background color, and expired badges with a red background color.

    Conditionally formatted data

    In this example, cells with employee ID numbers who have certification dates due to expire within 60 days are formatted in yellow, and ID numbers of employees with an expired certification are formatted in red. The rules are shown in the following image.

    Conditional formatting rules

    The first rule (which, if True, sets cell background color to red) tests a date value in column B against the current date (obtained by using the TODAY function in a formula). Assign the formula to the first data value in column B, which is B2. The formula for this rule is =B2<TODAY(). This formula tests the cells in column B (cells B2:B15). If the formula for any cell in column B evaluates to True, its corresponding cell in column A (for example, A5 corresponds to B5, A11 corresponds to B11), is then formatted with a red background color. After all the cells specified under Applies to are evaluated with this first rule, the second rule is tested. This formula checks if values in the B column are less than 60 days from the current date (for example, suppose today’s date is 8/11/2010). The cell in B4, 10/4/2010, is less than 60 days from today, so it evaluates as True, and is formatted with a yellow background color. The formula for this rule is =B2<TODAY()+60. Any cell that was first formatted red by the highest rule in the list is left alone.

    A rule higher in the list has greater precedence than a rule lower in the list. By default, new rules are always added to the top of the list and therefore have a higher precedence, so you’ll want to keep an eye on their order. You can change the order of precedence by using the Move Up and Move Down arrows in the dialog box.

    Move Up and Move Down arrows

  • What happens when more than one conditional formatting rule evaluates to True

    Sometimes you have more than one conditional formatting rule that evaluates to True. Here’s how rules are applied, first when rules don’t conflict, and then when they do conflict:

    When rules don’t conflict     For example, if one rule formats a cell with a bold font and another rule formats the same cell with a red color, the cell is formatted with both a bold font and a red color. Because there is no conflict between the two formats, both rules are applied.

    When rules conflict     For example, one rule sets a cell font color to red and another rule sets a cell font color to green. Because the two rules are in conflict, only one can apply. The rule that is applied is the one that is higher in precedence (higher in the list in the dialog box).

  • How pasting, filling, and the Format Painter affect conditional formatting rules

    While editing your worksheet, you may copy and paste cell values that have conditional formats, fill a range of cells with conditional formats, or use the Format Painter. These operations can affect conditional formatting rule precedence in the following way: a new conditional formatting rule based on the source cells is created for the destination cells.

    If you copy and paste cell values that have conditional formats to a worksheet opened in another instance of Excel (another Excel.exe process running at the same time on the computer), no conditional formatting rule is created in the other instance and the format is not copied to that instance.

  • What happens when a conditional format and a manual format conflict

    If a conditional formatting rule evaluates as True, it takes precedence over any existing manual format for the same selection. This means that if they conflict, the conditional formatting applies and the manual format does not. If you delete the conditional formatting rule, the manual formatting for the range of cells remains.

    Manual formatting is not listed in the Conditional Formatting Rules Manager dialog box nor is it used to determine precedence.

  • Controlling when rule evaluation stops by using the Stop If True check box

    For backwards compatibility with versions of Excel earlier than Excel 2007, you can select the Stop If True check box in the Manage Rules dialog box to simulate how conditional formatting might appear in those earlier versions of Excel that do not support more than three conditional formatting rules or multiple rules applied to the same range.

    For example, if you have more than three conditional formatting rules for a range of cells, and are working with a version of Excel earlier than Excel 2007, that version of Excel:

    • Evaluates only the first three rules.

    • Applies the first rule in precedence that is True.

    • Ignores rules lower in precedence if they are True.

    The following table summarizes each possible condition for the first three rules:

    If rule

    Is

    And if rule

    Is

    And if rule

    Is

    Then

    One

    True

    Two

    True or False

    Three

    True or False

    Rule one is applied and rules two and three are ignored.

    One

    False

    Two

    True

    Three

    True or False

    Rule two is applied and rule three is ignored.

    One

    False

    Two

    False

    Three

    True

    Rule three is applied.

    One

    False

    Two

    False

    Three

    False

    No rules are applied.

    You can select or clear the Stop If True check box to change the default behavior:

    • To evaluate only the first rule, select the Stop If True check box for the first rule.

    • To evaluate only the first and second rules, select the Stop If True check box for the second rule.

    You can’t select or clear the Stop If True check box if the rule formats by using a data bar, color scale, or icon set.

If you’d like to watch a video showing how to manage conditional formatting rules, see Video: Manage conditional formatting.

The order in which conditional formatting rules are evaluated — their precedence — also reflects their relative importance: the higher a rule is on the list of conditional formatting rules, the more important it is. This means that in cases where two conditional formatting rules conflict with each other, the rule that is higher on the list is applied and the rule that is lower on the list is not applied.

  1. On the Home tab, in the Styles group, click the arrow next to Conditional Formatting, and then click Manage Rules.

    Conditional Formatting menu with Manage Rules highlighted

    The Conditional Formatting Rules Manager dialog box appears.

    The conditional formatting rules for the current selection are displayed, including the rule type, the format, the range of cells the rule applies to, and the Stop If True setting.

    If you don’t see the rule that you want, in the Show formatting rules for list box, make sure that the right range of cells, worksheet, table, or PivotTable report is selected.

  2. Select a rule. Only one rule can be selected at a time.

  3. To move the selected rule up in precedence, click Move Up. To move the selected rule down in precedence, click Move Down.

    Move Up and Move Down arrows

  4. Optionally, to stop rule evaluation at a specific rule, select the Stop If True check box.

Clear conditional formatting on a worksheet    

  • On the Home tab, click Conditional Formatting > Clear Rules > Clear Rules from Entire Sheet.

Follow these steps if you have conditional formatting in a worksheet, and you need to remove it.

For an entire
worksheet

  • On the Home tab, click Conditional Formatting > Clear Rules > Clear Rules from Entire Sheet.

In a range of cells

  1. Select the cells that contain the conditional formatting.

  2. Click the Quick Analysis Lens button image button that appears to the bottom right of the selected data.

    Notes: 
    Quick Analysis Lens will not be visible if:

    • All of the cells in the selected range are empty, or

    • There is an entry only in the upper-left cell of the selected range, with all of the other cells in the range being empty.

  3. Click Clear Format.

    Clear option

Find and remove the same conditional formats throughout a worksheet

  1. Click on a cell that has the conditional format that you want to remove throughout the worksheet.

  2. On the Home tab, click the arrow next to Find & Select, and then click Go To Special.

  3. Click Conditional formats.

  4. Click Same under Data validation. to select all of the cells that contain the same conditional formatting rules.

  5. On the Home tab, click Conditional Formatting > Clear Rules > Clear Rules from Selected Cells.

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

Tip: The following sections use examples so you can follow along in Excel for the web. To start, download the Conditional Formatting Examples workbook and save it to OneDrive. Then, open OneDrive in a web browser and select the downloaded file.

  1. Select the cells you want to format, then select Home > Styles > Conditional Formatting > New Rule. You can also open the Conditional Formatting pane and create a new rule without first selecting a range of cells.

    New Rule step 1

  2. Verify or adjust the cells in Apply to range.

  3. Choose a Rule Type and adjust the options to meet your needs. 

  4. When finished, select Done and the rule will be applied to your range.

  1. Select a cell which has a conditional format you want to change. Or you can select Home > Styles > Conditional Formatting > Manage Rules to open the Conditional Formatting task pane and select an existing rule.

  2. The Conditional Formatting task pane displays any rules which apply to specific cells or ranges of cells.

    Image showing step 2 of editing a Conditional Formatting rule

  3. Hover over the rule and select Edit by clicking the pencil icon. This opens the task pane for rule editing. 

  4. Modify the rule settings and click Done to apply the changes.

The Conditional Formatting task pane provides everything you need for creating, editing, and deleting rules. Use Manage Rules to open the task pane and work with all the Conditional Formatting rules in a selection or a sheet.

  1. In an open workbook, select Home > Styles > Conditional Formatting > Manage Rules.

  2. The Conditional Formatting task pane opens and displays the rules, scoped to your current selection. 

Manage Rules in the task pane

From here, you can: 

  • Choose a different scope on the Manage Rules in menu — for example, choosing this sheet tells Excel to look for all rules on the current sheet.

  • Add a rule by selecting New Rule (the plus sign).

  • Delete all rules in scope by selecting Delete All Rules (the garbage can).

You can use a formula to determine how Excel evaluates and formats a cell.  Open the Conditional Formatting pane and select an existing rule or create a new rule.

In the Rule Type dropdown, select Formula.

Select Formula Rule

Enter the formula in the box. You can use any formula that returns a logical value of TRUE (1) or FALSE (0), but you can use AND and OR to combine a set of logical checks.

For example, =AND(B3=»Grain»,D3<500) is true for a cell in row 3 if both B3=»Grain» and D3<500 are true.

Formula rule type

You can clear conditional formatting in selected cells or the entire worksheet.

  • To clear conditional formatting in selected cells, select the cells in the worksheet. Then Select Home > Styles > Conditional Formatting > Clear Rules > Clear Rules from Selected Cells.

  • To clear conditional formatting in the entire worksheet, select Home > Styles > Conditional Formatting > Clear Rules > Clear Rules from Entire Sheet.

  • To delete conditional formatting rules, select Home > Styles > Conditional Formatting >Manage Rules and use the delete (garbage can) on a specific rule or the Delete all rules button.

Color scales are visual guides which help you understand data distribution and variation. Excel offers both two-color scales and three-color scales. 

A two-color scale helps you compare a range of cells by using a gradation of two colors. The shade of the color represents higher or lower values. For example, in a green and yellow color scale, you can specify that higher value cells be more green and lower value cells have a more yellow.

Two color scale formatting

A three-color scale helps you compare a range of cells by using a gradation of three colors. The shade of the color represents higher, middle, or lower values. For example, in a green, yellow, and red color scale, you can specify that higher value cells have a green color, middle value cells have a yellow color, and lower value cells have a red color.

Three color scale formatting

Tip: You can sort cells that have one of these formats by their color — just use the context menu.

  1. Select the cells that you want to conditionally format using color scales.

  2. Click Home > Styles > Conditional Formatting > Color Scales and select a color scale.

A data bar helps you see the value of a cell relative to other cells. The length of the data bar represents the value in the cell. A longer bar represents a higher value, and a shorter bar represents a lower value. Data bars are useful in spotting higher and lower numbers, especially with large amounts of data, such as top selling and bottom selling toys in a holiday sales report.

Data bars

  1. Select the cells that you want to conditionally format.

  2. Select Home > Styles > Conditional Formatting > Data Bars and select a style. 

Use an icon set to annotate and classify data into three to five categories separated by a threshold value. Each icon represents a range of values. For example, in the 3 Arrows icon set, the green up arrow represents higher values, the yellow sideways arrow represents middle values, and the red down arrow represents lower values.

Icon set

  1. Select the cells that you want to conditionally format.

  2. Select Home > Styles > Conditional Formatting > Icon Sets and choose an icon set.

This option lets you highlight specific cell values within a range of cells based on their specific contents. This can be especially useful when working with data sorted using a different range.

For example, in an inventory worksheet sorted by categories, you could highlight the names of products where you have fewer than 10 items in stock so it’s easy to see which products need restocking without resorting the data. 

  1. Select the cells that you want to conditionally format.

  2. Select Home > Styles > Conditional Formatting > Highlight Cell Rules.

  3. Select the comparison, such as Between, Equal To, Text That Contains, or A Date Occurring.

You can highlight the highest and lowest values in a range of cells which are based on a specified cutoff value.

Some examples of this would include highlighting the top five selling products in a regional report, the bottom 15% products in a customer survey, or the top 25 salaries in a department.

  1. Select the cells that you want to conditionally format.

  2. Select Home > Styles > Conditional Formatting > Top/Bottom Rules.

  3. Select the command you want, such as Top 10 items or Bottom 10 %.

  4. Enter the values you want to use, and select a format (fill, text, or border color).

You can highlight values above or below an average or standard deviation in a range of cells.

For example, you can find the above-average performers in an annual performance review, or locate manufactured materials that fall below two standard deviations in a quality rating.

  1. Select the cells that you want to conditionally format.

  2. Select Home> Styles > Conditional Formatting > Top/Bottom Rules.

  3. Select the option you want, such as Above Average or Below Average.

  4. Enter the values you want to use, and select a format (fill, text, or border color).

  1. Select the cells that you want to conditionally format.

  2. Select Home > Styles > Conditional Formatting > Highlight Cell Rules > Duplicate Values.

  3. Enter the values you want to use, and select a format (fill, text, or border color).

If you want to apply an existing formatting style to other cells on your worksheet, use Format Painter to copy the conditional formatting to that data.

  1. Click the cell that has the conditional formatting you want to copy.

  2. Click Home > Format Painter.

    Copy and Paste buttons on the Home tab

    The pointer will change to a paintbrush.

    Tip: You can double-click Format Painter if you want to keep using the paintbrush to paste the conditional formatting in other cells.

  3. Drag the paintbrush across the cells or range of cells you want formatted.

  4. To stop using the paintbrush, press Esc.

Note: If you’ve used a formula in the rule that applies the conditional formatting, you might have to adjust relative and absolute references in the formula after pasting the conditional format. For more information, see Switch between relative, absolute, and mixed references.

Note: You can’t use conditional formatting on external references to another workbook.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

See Also

Conditional formatting compatibility issues

Skip to content

Как сделать условное форматирование в Excel? Инструкции с примерами.

В этой статье вы найдете множество быстрых способов как сделать условное форматирование строк, столбцов и отдельных ячеек в MS Excel 2016, 2013 и 2010. Мы рассмотрим, как можно применить различное оформление к данным, которые соответствуют определенным критериям. Это может помочь указать на наиболее важную информацию в ваших электронных таблицах.

Всем известно, что изменить фон ячейки легко. Это можно совершить, просто нажав кнопку «Цвет заливки». Но что, если вы хотите изменить оформление вашей таблицы при выполнении какого-то условия? Более того, что, если вам нужно, чтобы он изменялся автоматически при внесении изменений в таблицу? Условное форматирование для этого является действительно мощной и полезной функцией. Далее в этой статье вы найдете ответы на эти вопросы и прочтете несколько полезных советов, которые помогут выбрать правильный метод условного форматирования для каждой конкретной задачи.

В то же время изменение внешнего вида в связи с содержанием текущей либо какой-то иной ячейки либо от иных условий часто считается одной из самых сложных и непонятных функций, особенно для новичков. Если вас тоже пугает эта функция, не бойтесь! На самом деле, она очень удобна и проста в использовании, и вы убедитесь в этом всего за 5 минут после прочтения этого руководства. А теперь взгляните, сколько всего мы можем сделать!

  1. Где находится форматирование по условию в Excel?
  2. Как автоматически изменить цвет при помощи условного форматирования?
  3. Условное форматирование Excel по значению ячейки.
  4. Использование абсолютных и относительных ссылок в правилах.
  5. Как использовать в правилах ссылку на соседние листы?
  6. Приоритет выполнения правил — это важно!
  7. Как редактировать условное форматирование?
  8. А если забыл, где какие правила создавал?
  9. Как можно скопировать условное форматирование?
  10. Как убрать условное форматирование?
  11. Почему не работает?

Кроме того, если вы будете использовать форматирование по условию, то имейте в виду, что оно имеет более высокий приоритет по сравнению с обычным оформлением вручную, которое вы можете сделать через меню Главная – Формат.

Вы можете применить условное форматирование к одной или нескольким позициям, строкам, столбцам или всей таблице на основе их содержимого или при выполнении какого-то другого условия. Это делается путем создания правил (условий), в которых вы определяете, когда и как следует изменить вид выбранных клеток таблицы.

Где находится форматирование по условию в Excel?

Это очень просто: на вкладке «Главная», а в более старых версиях — группа «Стили».

Эта функция включает в себя стандартный набор заранее определенных правил и инструментов. Но главное, у пользователя есть возможность самому придумать и настроить необходимый алгоритм закраски и выделения, используя свои формулы.

Теперь, когда вы знаете, как активировать функцию условного форматирования в Excel, давайте продолжим и посмотрим, какие у вас есть варианты форматирования и как вы можете создавать свои собственные правила.

Как автоматически изменить цвет при помощи условного форматирования?

Чтобы по-настоящему использовать возможности условного формата в Excel, вы должны научиться создавать различные типы правил.

Правила условного форматирования определяют 2 ключевых момента:

  • К каким ячейкам должно применяться условное форматирование,
  • Какие условия должны быть выполнены.

Я покажу вам, как применить условное форматирование в Excel 2016, потому что это, кажется, самая популярная версия в наши дни. Однако оно практически не отличается от форматирования в версиях 2007, 2013 и 2010. Поэтому у вас не возникнет проблем с выделением цветом нужной информации независимо от того, какая версия установлена ​​на вашем компьютере.

Задача: у вас есть таблица или диапазон данных, и вы хотите изменить фон ячеек на основе их содержания. Кроме того, вы хотите, чтобы он менялся динамически, отражая изменения данных.

Решение: Предположим, у вас в таблице — данные о продажах шоколада различным покупателям. Необходимо в таблице Excel закрасить цветом клетки с количеством следующим образом: менее 100 единиц товара – красным, 100 и более – зелёным.

Итак, вот что вы делаете шаг за шагом:

Способ 1 — Используем стандартные возможности.

Самый простой способ — воспользоваться стандартными правилами выделения ячеек. Эти заготовки включают в себя самые простые и распространенные случаи. Но сначала выберите таблицу или диапазон, где вы хотите изменить фон ячеек. Мы взяли $D$2:$D$21.

Перейдите на вкладку «Главная» и выберите

(1) > «Правила выделения ячеек» (2) > «Меньше» (3). В более ранних версиях программы нужное нам меню располагается в группе «Стили».

Конечно, можно использовать любой другой тип правил, который больше подходит для ваших данных, например:

  • Значение больше, меньше или равно.
  • Выделить текст, содержащий определённые слова или символы.
  • Выделить дубликаты.
  • Форматирование конкретных дат.

изменяем цвет по условию

В диалоговом окне укажите, что числа должны быть меньше 100, также выберите вариант выделения.

выделяем значения меньше определенного

В первом поле задается условие, а во втором указывают, каким образом отформатировать полученный результат. Обратите внимание, выбрать можно цвет фона и текста из предложенных в списке. Но если хочется применить иные оттенки – сделать это можно, перейдя в «Пользовательский формат».

В результате клетки таблицы с количеством меньше 100 окрасились в красный цвет.

Приступаем к созданию второго правила. С этой же областью таблицы проделайте те же операции, только выберите на третьем шаге пункт «Больше».

В результате получим нужную нам раскраску.

формат зависит от содержимого

Это самый простой вариант заливки ячеек.

С помощью использованных нами «Правил выделения ячеек»:

  • находят в таблице числа, которые больше определенного;
  • выбирают те, которые меньше определенного;
  • указывают на числа, находящиеся в пределах нужного интервала;
  • определяют равные какому-то числу;
  • помечают в выбранных текстовых полях только те, которые необходимы;
  • отмечают столбцы и числа за нужную дату;
  • находят повторяющиеся текст или числа;
  • придумывают прочие правила.

Способ 2 — Как самому создать правило форматирования?

Тот же результат мы можем получить и чуть иначе. Если ни одно из готовых правил форматирования не отвечает вашим потребностям, вы можете создать новое с нуля. Для этого вновь перейдите на вкладку «Главная» и выберите (1 на рисунке) > «Создать правило» (2).

Затем выберите пункт «Форматировать только ячейки, которые содержат» (3). Чуть ниже укажите, что число должно быть меньше (4) цифры «100» (5).

И далее укажите, как это все должно выглядеть. Нажмите кнопку «Формат» (6).

Выберите «красный» на открывшейся вкладке «Заливка».

Нажмите «ОК».

создаем правило

При создании правила в окне « Формат ячеек» переключайтесь между вкладками « Шрифт» , « Граница» и « Заливка», чтобы выбрать стиль шрифта, стиль рамки и цвет фона соответственно. На вкладках Шрифт и Заливка вы сразу увидите предварительный просмотр вашего пользовательского формата.
Когда закончите, нажмите кнопку ОК в нижней части окна.

как должно выглядеть выделение?

Подсказка:
Если вам нужно больше цветов фона или шрифта, чем предусмотрено в стандартной палитре, нажмите кнопку «Другие цвета…» на вкладках «Заливка» и «Шрифт»..
Если вы хотите применить градиент цвета фона , нажмите кнопку «Способы заливки» и выберите нужные параметры.
Нажмите кнопку ОК, чтобы закрыть окно и проверить, правильно ли применяется условное форматирование к вашим данным.

Повторите все то же самое еще раз, только измените условие: цифра должна быть больше или равна 100. И новый цвет условного форматирования, конечно же, выберите сейчас зеленый.

Способ 3 — Применяем собственную формулу в правиле условного форматирования.

И, наконец, третий способ – самый сложный, но зато самый универсальный и с большими возможностями. Чуть ранее мы создали правила форматирования, указав определенные числа, дату либо текст. Однако в некоторых случаях имеет смысл основывать условие на значении определенной ячейки. Преимущество этого подхода состоит в том, что в зависимости от того, как значение этой ячейки изменится в будущем, ваше условное форматирование будет корректироваться автоматически и отражать изменение данных.

Вновь перейдите на вкладку «Главная», (в старых версиях программы — в группу «Стили») и выберите (1) > «Создать правило» (2).

Затем выберите пункт «Использовать формулу для определения форматируемых ячеек» (3). Теперь нужно указать диапазон, в котором мы хотим что-то выделить. Для этого нажмите на пиктограмму со стрелкой вверх (4) и укажите мышкой начало диапазона – D2. Следите за тем, чтобы ссылка не была абсолютной (можно для этого использовать F4).  И в конце просто допишите условие: “<100” (5), как это показано на рисунке.

используем формулу

Осталось только определить новые правила форматирования. Нажмите кнопку «Формат» (6).

Выберите красный на вкладке «Заливка».

Повторите создание условия еще раз, только выражение запишите D2>=100 и выберите зеленый.

Вы спросите: «А зачем все так сложно, если есть более простой вариант?» Дело в том, что использование формулы – более универсальный подход, который мы в дальнейшем будем еще неоднократно применять.

Итак, цель достигнута: фон выбранных ячеек изменяется от их наполнения.

Совет: вы можете использовать тот же метод не только для закраски, но и для изменения оформления шрифта. Для этого просто перейдите на вкладку «Шрифт» в диалоговом окне «Формат», которое мы обсуждали на шаге 6, и выберите предпочитаемый вариант оформления.

Условное форматирование Excel по значению ячейки.

В обоих предыдущих примерах мы создали правила форматирования, прямо указав числа — ограничения. Но чаще всего следует создавать критерий форматирования на основе значений ячеек. Как это сделать? Предположим, в таблице записаны ежемесячные продажи нескольких товаров. Нужно выделить цветом те цифры в декабре, которые были больше январских, в начале года.

Выделяем область для применения условного форматирования М2:М16 и затем выбираем пункт «Создать правило». В описании правила запишем выражение:

=M2>B2

Обратите внимание, что здесь используются относительные ссылки, чтобы программа могла последовательно перебрать все ячейки указанной ей области, и при этом каждой ячейке из столбца М соответствовала ячейка из столбца В, расположенная в той же строке и относящаяся к тому же самому товару.

Отображение выделенных ячеек настройте так же, как мы это рассматривали ранее.

Как видно на рисунке, созданное нами правило условного форматирования работает правильно и выделяет декабрьские продажи тех товаров, которые выросли по сравнению с январём.

Использование абсолютных и относительных ссылок в правилах.

Для того, чтобы было проще изменять условия выделения определенных значений в таблице Эксель, запишем некоторые параметры отбора в специально отведённые для этого ячейки.

Задача: выделить в таблице заказы с количеством менее 50 и более 100 ед.

Наши ограничения записываем в D1 и D2. Далее создаем первое правило условного форматирования для диапазона E5:E24.

=E5>$D$2

Абсолютная ссылка на D2 означает, что каждая из ячеек нашего диапазона сравнения должна сравниваться именно с D2. А относительная ссылка на первую ячейку нашей выделенной области E5 предписывает программе начать именно с этой позиции и последовательно двигаться вниз по столбцу, сравнивая количество с пороговым значением 100.

Как обычно, выбираем цвет заливки в случае выполнения условия.

Аналогичным образом для E5:E24 создаем второе правило

=E5<$D$1

В результате часть столбца окрасится зелёным, часть — жёлтым, а количество между 50 и 100 останется неокрашенным.

А теперь давайте усложним задачу — закрасим цветом не отдельные ячейки, а строки таблицы целиком. Для этого нам всего лишь понадобится изменить несколько ссылок в наших правилах.

Прежде всего, заново обозначим диапазон условного форматирования. Теперь это будет $A$5:$G$24.

В правило форматирования внесем небольшое изменение:

=$E5>$D$2

Как видите, у нас появилась абсолютная ссылка на столбец E. А на строку ссылка осталась относительной, без знака $. Для программы это означает, что нужно использовать данные строки целиком, и окрасить ее тоже всю, а не отдельную ячейку.

Аналогично второе условие мы меняем с E5<$D$1 на $E5<$D$1.

условное форматирование строки целиком

В то же время ссылка на D2 так и остается абсолютной, поскольку условие записано именно в этой ячейке. В результате получаем «полосатую» таблицу, где цветом выделены уже целые строки. И вся хитрость заключается в грамотном использовании абсолютных ссылок в правилах.

Вывод. Давайте постараемся запомнить несложные принципы использования ссылок в правилах:

  • если сравниваются попарно 2 столбца, то используют относительные ссылки (M2>B2).
  • если значения в столбце сопоставляются с определённой ячейкой, то на нее обязательно должна быть абсолютная ссылка ($D$1).
  • когда нужно закрасить по условию строку целиком, то ссылка на эту строку должна быть относительной ($E5)
  • когда нужно закрасить столбец целиком, то ссылка на него должна быть относительной (E$5)

Как использовать в правилах ссылку на соседние листы?

В последних версиях начиная с 2010 года, в формулах условия вы можете спокойно использовать ссылки на данные с других листов. Делается это точно так же, как и в обычных формулах.

В более ранних версиях программы – 2007 и 2003, это ограничение можно легко обойти, использовав именованные диапазоны. Вы просто присваиваете определенные имена диапазонам на текущем или на соседних листах, а затем используете эти имена в функциях.

В частности, вместо

=ЕСЛИ(‘Formatting (Лист2)’!$E$2:$E$21>5000;1;0)

можно работать по формуле

=ЕСЛИ(продажи>5000;1;0)

Как вы понимаете, диапазон ‘Formatting (Лист2)’!$E$2:$E$21 получил имя «продажи» и теперь к нему можно обратиться из любого места вашей рабочей книги.

Приоритет выполнения правил — это важно!

При использовании условного форматирования в Excel вы не ограничены только одним правилом на ячейку. Вы можете применять столько правил, сколько требует логика вашего проекта. В том случае, если в вашей таблице используется несколько правил, то важно, в каком порядке они выполняются.

Если выбрать меню «Управление правилами» и указать там «Текущий лист», то вы увидите список имеющихся правил.

В этой таблице мы хотим выделить желтым цветом предстоящие в недалёком будущем отгрузки, а вот те из них, которые должны произойти сегодня или завтра, обозначить красным. Ведь к ним должно быть повышенное внимание и их нужно срочно выполнить.

очередность выполнения правил

Сначала создадим первое условие:

=$E5>$C$2

Как видим, сюда попадают все строки, в которых дата отгрузки больше текущей даты, записанной в ячейке C2.

Затем создаем второе условие, которое как бы будет являться подмножеством первого. Выделяем только ячейки, в которых ИЛИ дата отгрузки равна текущей $E$5=$C$2, ИЛИ дата отгрузки больше текущей на 1 день $E5-$C$2=1. Если хотя бы одно из этих требований выполняется, то строка будет закрашена красным.

=ИЛИ($E5-$C$2=1;$E$5=$C$2)

Важно! Правила, расположенные выше в списке, имеют более высокий приоритет (1 и 2 на рисунке вверху). Новые правила всегда добавляются в начало списка и по этой причине имеют более высокий приоритет. Результат их работы не может быть изменен действием предшествующих правил, расположенных ниже.

Однако, порядок выполнения всегда можно изменить в этом же окне при помощи стрелок «Вверх» и «Вниз» (3).

Как редактировать условное форматирование?

Для того, чтобы изменить ранее созданное условие, нужно в первую очередь посмотреть, какие условия мы применяем к таблице и далее просто выбрать нужное правило. Последовательность действий та же, что мы рассмотрели чуть выше. Но на всякий случай еще раз повторю ее на скриншоте: нам нужен раздел «Управление правилами», затем указать, что рассматриваем текущий лист.

При нажатии иконки «Изменить…» мы попадаем в уже знакомое нам меню создания правила. Только все поля там уже заполнены текущими значениями. Остается только изменить то, что необходимо, и нажать «Ок».

А если забыл, где какие правила создавал?

В виду того, что этот способ имеет приоритет над обычным оформлением, вы можете получить внешний вид таблицы не совсем таким, как ожидали. Особенно, если забудете, где и какие правила создавали. Итак, как нам быстро найти в таблице все ячейки с условным форматированием?

Один их простых способов обнаружить такие нестандартные места таблицы – использовать меню Главная – Найти и выделить – …… в последних версиях Excel. Или же Главная – Редактирование – Найти и выделить – … в более ранних версиях.

Но в результате вы просто увидите те области таблицы, в которых применено условное форматирование. И не более того. Какие именно там условия изменения оформления — пока неизвестно. В любом случае вам, скорее всего, придется копать глубже и разбираться, какие же условия там применены.

Поэтому лучше всего просто выберите раздел «Управление правилами» — текущий лист. Этот процесс мы уже дважды описывали в предыдущих разделах, поэтому, думаю, проблем здесь не возникнет.

Вы увидите все созданные вами правила, а также приоритет их выполнения. Напомним, что наивысший приоритет имеют правила, находящиеся в начале списка: чем выше, тем важнее. Также указаны области, к которым применяются созданные форматы. Думаю, здесь разобраться будет совершенно несложно.

Как можно скопировать условное форматирование?

Вот несколько способов  для копирования правил.

Копировать формат по образцу

Можно скопировать так же, как и обычный формат.

На вкладке «Главная» в самом начале ленты расположена группа «Буфер обмена». В ней вы видите пиктограмму кисти  – формат по образцу (в разных версия выглядит по-разному, но называется одинаково). Клик по ней копирует не только формат выделенных ячеек, но и условия для него, если таковые имеются. Следующим действием необходимо выделить те ячейки, в которые данное оформление необходимо перенести.

Имейте в виду, что описанный способ перенесет абсолютно все форматы, в том числе и установленные вручную.

Копирование через вставку.

Альтернативным вариантом дублировать формат является специальный способ вставки.

Скопируйте ячейки с нужным условным форматом любым привычным для вас способом. Выделите диапазон, на который требуется перенести формат (можете выделить и не смежные, зажав клавишу CTRL), а затем по щелчку правой кнопки мыши выберите пункт «Специальная вставка…». Тогда программа отобразит окно, где потребуется установить переключатель на точке «форматы», после чего нажать «OK».

Управление правилами.

Можно воспользоваться диспетчером правил.

Пройдите по следующему пути: -> «Управление правилами…».

Из раскрывающего списка «Показать правила…» выберите пункт «Этот лист». Вы сможете увидеть все правила, которые действуют на текущем листе.

В столбце списка правил «Применяется к» указаны диапазоны, на которые распространяется каждое правило. Допишите в это поле через точку с запятой нужные адреса ячеек, чтобы применить и к ним ранее созданные условия.

Данный способ более трудоемкий, чем предыдущие два. Но его прелесть в том, что он позволяет распространять только нужные правила. Это особенно полезно тогда, когда к копируемым ячейкам применяется несколько условий одновременно, а скопировать нужно только одно из них.

Как убрать условное форматирование?

Эта операция такая же несложная, как и создание правила. Выберите , и затем – «Удалить правила». Вам будет предложено либо удаление из выделенного диапазона данных, либо вовсе всех правил на листе. Но имейте в виду, что при этом вы удалите всё, что было ранее создано. А ведь, возможно, что-то вы хотели бы сохранить.

Поэтому существует и более тонкий инструмент, которым мы рекомендовали бы пользоваться и для редактирования, и для их удаления.

Используйте последний пункт выпадающего меню: «Управление правилами».

Здесь вы видите все правила на текущем листе, к каким диапазонам они относятся и что делают. Поэтому гораздо проще выбрать определенное правило и удалить его.

Либо изменить, если в этом есть необходимость.

Почему не работает?

Если вы не получаете ожидаемого результата, то в первую очередь следует убедиться, верно ли работает созданное вами правило условного форматирования. Для этого вы можете скопировать формулу из правила в любую пустую ячейку и посмотреть, какой результат будет получен. Если вы форматируете по условию целый столбец цифр, то выберите пустое место справа от вашей таблицы.

Если результатом выполнения формулы-условия будет ИСТИНА, значит, должно быть применено условное форматирование. Естественно, если ЛОЖЬ, то — нет. Давайте вернемся в одной из наших задач и выполним такую отладку правил форматирования.

отладка правил условного форматирования

В столбец I скопируем формулу первого условия, в K — второго. Зацепите мышкой правый нижний уголок ячейки с формулой и протащите ее вниз на всю высоту таблицы. Получим полную картину для каждой из ячеек нашего диапазона. Как видите, ИСТИНА и ЛОЖЬ точно соответствуют закраске столбца K, который мы, собственно, и проверяли. В I2 мы получили ИСТИНА, поэтому цвет — зелёный. В J9 ответ также положительный, поэтому цвет — желтый. И так далее.

Если формула сложная, можно разбить ее на части и применить тот же метод отладки.

Надеемся, что вы нашли ответы на интересующие вас вопросы по условному форматированию в нашей инструкции.

Тем не менее, если всё же что-то не получается или не работает – пишите в комментариях ниже. Мы постараемся вам ответить либо даже сделаем отдельный материал, посвященный вашей проблеме.

Удачи!

Еще полезные примеры и советы:

Формат времени в Excel Вы узнаете об особенностях формата времени Excel, как записать его в часах, минутах или секундах, как перевести в число или текст, а также о том, как добавить время с помощью…
как форматировать Google таблицу Как сделать пользовательский числовой формат в Excel В этом руководстве объясняются основы форматирования чисел в Excel и предоставляется подробное руководство по созданию настраиваемого пользователем формата. Вы узнаете, как отображать нужное количество десятичных знаков, изменять выравнивание или цвет шрифта,…
7 способов поменять формат ячеек в Excel Мы рассмотрим, какие форматы данных используются в Excel.  Кроме того, расскажем, как можно быстро изменять внешний вид ячеек самыми различными способами. Когда дело доходит до форматирования ячеек в Excel, большинство…
Как удалить формат ячеек в Excel В этом коротком руководстве показано несколько быстрых способов очистки форматирования в Excel и объясняется, как удалить форматы в выбранных ячейках. Самый очевидный способ сделать часть информации более заметной — это…
9 способов сравнить две таблицы в Excel и найти разницу В этом руководстве вы познакомитесь с различными методами сравнения таблиц Excel и определения различий между ними. Узнайте, как просматривать две таблицы рядом, как использовать формулы для создания отчета о различиях, выделить…

Содержание

  • Простейшие варианты условного форматирования
  • Правила выделения ячеек
  • Правила отбора первых и последних значений
  • Создание правил
  • Управление правилами
  • Вопросы и ответы

Условное форматирование в Microsoft Excel

Смотря на сухие цифры таблиц, трудно с первого взгляда уловить общую картину, которую они представляют. Но, в программе Microsoft Excel имеется инструмент графической визуализации, с помощью которого можно наглядно представить данные, содержащиеся в таблицах. Это позволяет более легко и быстро усвоить информацию. Данный инструмент называется условным форматированием. Давайте разберемся, как использовать условное форматирование в программе Microsoft Excel.

Простейшие варианты условного форматирования

Для того, чтобы произвести форматирование определенной области ячеек, нужно выделить эту область (чаще всего столбец), и находясь во вкладке «Главная», кликнуть по кнопке «Условное форматирование», которая расположена на ленте в блоке инструментов «Стили».

После этого, открывается меню условного форматирования. Тут представляется три основных вида форматирования:

  • Гистограммы;
  • Цифровые шкалы;
  • Значки.

Типы условного форматирования в Microsoft Excel

Для того, чтобы произвести условное форматирование в виде гистограммы, выделяем столбец с данными, и кликаем по соответствующему пункту меню. Как видим, представляется на выбор несколько видов гистограмм с градиентной и сплошной заливкой. Выберете ту, которая, на ваш взгляд, больше всего соответствует стилю и содержанию таблицы.

Выбор гистограммы в Microsoft Excel

Как видим, гистограммы появились в выделенных ячейках столбца. Чем большее числовое значение в ячейках, тем гистограмма длиннее. Кроме того, в версиях Excel 2010, 2013 и 2016 годов, имеется возможность корректного отображения отрицательных значений в гистограмме. А вот, у версии 2007 года такой возможности нет.

Гистограмма применена в Microsoft Excel

При использовании вместо гистограммы цветовой шкалы, также существует возможность выбрать различные варианты данного инструмента. При этом, как правило, чем большее значение расположено в ячейке, тем насыщеннее цвет шкалы.

Использование цветовой шкалы в Microsoft Excel

Наиболее интересным и сложным инструментом среди данного набора функций форматирования являются значки. Существует четыре основные группы значков: направления, фигуры, индикаторы и оценки. Каждый выбранный пользователем вариант предполагает использование разных значков при оценке содержимого ячейки. Вся выделенная область сканируется Excel, и все значения ячеек разделяются на части, согласно величинам, указанным в них. К самым большим величинам применяются значки зеленого цвета, к величинам среднего диапазона – желтого, и величины, располагающиеся в самой меньшей трети – помечаются значками красного цвета.

Значки при условном форматировании в Microsoft Excel

При выборе стрелок, в качестве значков, кроме цветового оформления, используется ещё сигнализирование в виде направлений. Так, стрелка, повернутая указателем вверх, применяется к большим величинам, влево – к средним, вниз – к малым. При использовании фигур, кругом помечаются самые большие величины, треугольником – средние, ромбом – малые.

Стрелки при условном форматировании в Microsoft Excel

Lumpics.ru

Правила выделения ячеек

По умолчанию, используется правило, при котором все ячейки выделенного фрагмента обозначаются определенным цветом или значком, согласно расположенным в них величинам. Но, используя меню, о котором мы уже говорили выше, можно применять и другие правила обозначения.

Кликаем по пункту меню «Правила выделения ячеек». Как видим, существует семь основных правил:

  • Больше;
  • Меньше;
  • Равно;
  • Между;
  • Дата;
  • Повторяющиеся значения.

Правила выделения ячеек в Microsoft Excel

Рассмотрим применение этих действий на примерах. Выделим диапазон ячеек, и кликнем по пункту «Больше…».

Переход к правилу выделения ячеек в Microsoft Excel

Открывается окно, в котором нужно установить, значения больше какого числа будут выделяться. Делается это в поле «Форматировать ячейки, которые больше». По умолчанию, сюда автоматически вписывается среднее значение диапазона, но можно установить любое другое, либо же указать адрес ячейки, в которой содержится это число. Последний вариант подойдёт для динамических таблиц, данные в которых постоянно изменяются, или для ячейки, где применяется формула. Мы для примера установили значение в 20000.

Установка границы для выделения ячеек в Microsoft Excel

В следующем поле, нужно определиться, как будут выделяться ячейки: светло-красная заливка и темно-красный цвет (по умолчанию); желтая заливка и темно-желтый текст; красный текст, и т.д. Кроме того, существует пользовательский формат.

Выбор цвета выделения в Microsoft Excel

При переходе на этот пункт, открывается окно, в котором можно редактировать выделения, практически, как угодно, применяя различные варианты шрифта, заливки, и границы.

Пользоательский формат в Microsoft Excel

После того, как мы определились, со значениями в окне настройки правил выделения, жмём на кнопку «OK».

Сохранение результатов в Microsoft Excel

Как видим, ячейки выделены, согласно установленному правилу.

Ячейки выделены согласно правилу в Microsoft Excel

По такому же принципу выделяются значения при применении правил «Меньше», «Между» и «Равно». Только в первом случае, выделяются ячейки меньше значения, установленного вами; во втором случае, устанавливается интервал чисел, ячейки с которыми будут выделяться; в третьем случае задаётся конкретное число, а выделяться будут ячейки только содержащие его.

Другие варианты выделения в Microsoft Excel

Правило выделения «Текст содержит», главным образом, применяется к ячейкам текстового формата. В окне установки правила следует указать слово, часть слова, или последовательный набор слов, при нахождении которых, соответствующие ячейки будут выделяться, установленным вами способом.

Выделение текст содержит в Microsoft Excel

Правило «Дата» применяется к ячейкам, которые содержат значения в формате даты. При этом, в настройках можно установить выделение ячеек по тому, когда произошло или произойдёт событие: сегодня, вчера, завтра, за последние 7 дней, и т.д.

Выделение ячеек по дате в Microsoft Excel

Применив правило «Повторяющиеся значения» можно настроить выделение ячеек, согласно соответствию размещенных в них данных одному из критериев: повторяющиеся это данные или уникальные.

Выделение повторяющихся значений в Microsoft Excel

Правила отбора первых и последних значений

Кроме того, в меню условного форматирования имеется ещё один интересный пункт – «Правила отбора первых и последних значений». Тут можно установить выделение только самых больших или самых маленьких значений в диапазоне ячеек. При этом, можно использовать отбор, как по порядковым величинам, так и по процентным. Существуют следующие критерии отбора, которые указаны в соответствующих пунктах меню:

  • Первые 10 элементов;
  • Первые 10%;
  • Последние 10 элементов;
  • Последние 10%;
  • Выше среднего;
  • Ниже среднего.

Правила отбора первых и последних ячеек в Microsoft Excel

Но, после того, как вы кликнули по соответствующему пункту, можно немного изменить правила. Открывается окно, в котором производится выбор типа выделения, а также, при желании, можно установить другую границу отбора. Например, мы, перейдя по пункту «Первые 10 элементов», в открывшемся окне, в поле «Форматировать первые ячейки» заменили число 10 на 7. Таким образом, после нажатия на кнопку «OK», будут выделяться не 10 самых больших значений, а только 7.

Установка правила отбора первых и последних ячеек в Microsoft Excel

Создание правил

Выше мы говорили о правилах, которые уже установлены в программе Excel, и пользователь может просто выбрать любое из них. Но, кроме того, при желании, пользователь может создавать свои правила.

Для этого, нужно нажать в любом подразделе меню условного форматирования на пункт «Другие правила…», расположенный в самом низу списка». Или же кликнуть по пункту «Создать правило…», который расположен в нижней части основного меню условного форматирования.

Переход к созданию правила в Microsoft Excel

Открывается окно, где нужно выбрать один из шести типов правил:

  1. Форматировать все ячейки на основании их значений;
  2. Форматировать только ячейки, которые содержат;
  3. Форматировать только первые и последние значения;
  4. Форматировать только значения, которые находятся выше или ниже среднего;
  5. Форматировать только уникальные или повторяющиеся значения;
  6. Использовать формулу для определения форматируемых ячеек.

Типы правил в Microsoft Excel

Согласно выбранному типу правил, в нижней части окна нужно настроить изменение описания правил, установив величины, интервалы и другие значения, о которых мы уже говорили ниже. Только в данном случае, установка этих значений будет более гибкая. Тут же задаётся, при помощи изменения шрифта, границ и заливки, как именно будет выглядеть выделение. После того, как все настройки выполнены, нужно нажать на кнопку «OK», для сохранения проведенных изменений.

Опивание правила в Microsoft Excel

Управление правилами

В программе Excel можно применять сразу несколько правил к одному и тому же диапазону ячеек, но отображаться на экране будет только последнее введенное правило. Для того, чтобы регламентировать выполнение различных правил относительно определенного диапазона ячеек, нужно выделить этот диапазон, и в основном меню условного форматирования перейти по пункту управление правилами.

Переход к управлению правидлами в Microsoft Excel

Открывается окно, где представлены все правила, которые относятся к выделенному диапазону ячеек. Правила применяются сверху вниз, так как они размещены в списке. Таким образом, если правила противоречат друг другу, то по факту на экране отображается выполнение только самого последнего из них.

Окно управления праилами в Microsoft Excel

Чтобы поменять правила местами, существуют кнопки в виде стрелок направленных вверх и вниз. Для того, чтобы правило отображалось на экране, нужно его выделить, и нажать на кнопку в виде стрелки направленной вниз, пока правило не займет самую последнюю строчу в списке.

Изменение порядка правил в Microsoft Excel

Есть и другой вариант. Нужно установить галочку в колонке с наименованием «Остановить, если истина» напротив нужного нам правила. Таким образом, перебирая правила сверху вниз, программа остановится именно на правиле, около которого стоит данная пометка, и не будет опускаться ниже, а значит, именно это правило будет фактически выполнятся.

Оставить если истина в Microsoft Excel

В этом же окне имеются кнопки создания и изменения выделенного правила. После нажатия на эти кнопки, запускаются окна создания и изменения правил, о которых мы уже вели речь выше.

Создание и изменение правила в Microsoft Excel

Для того, чтобы удалить правило, нужно его выделить, и нажать на кнопку «Удалить правило».

Удаление правила в Microsoft Excel

Кроме того, можно удалить правила и через основное меню условного форматирования. Для этого, кликаем по пункту «Удалить правила». Открывается подменю, где можно выбрать один из вариантов удаления: либо удалить правила только на выделенном диапазоне ячеек, либо удалить абсолютно все правила, которые имеются на открытом листе Excel.

Удаление правил вторым способом в Microsoft Excel

Как видим, условное форматирование является очень мощным инструментом для визуализации данных в таблице. С его помощью, можно настроить таблицу таким образом, что общая информация на ней будет усваиваться пользователем с первого взгляда. Кроме того, условное форматирование придаёт большую эстетическую привлекательность документу.

How to Use Conditional Formatting in Excel

Conditional formatting is one of my favorite features in both Excel and Google Sheets. I love the way it can make a boring hard-to-interpret spreadsheet more interesting and easier to use.

Conditional formatting is mostly used for data analysis, such as adding color scales, highlighting high and low values, identifying duplicates, and marking outliers. Conditional formatting can be also used for graphical interface elements such as progress bars, graying out completed tasks, changing number formats, or displaying a gantt chart.

In this article, I’ll show over 20 different ways that you can use conditional formatting, starting with some basics and presenting some advanced techniques as well. Many of the examples come from templates that you can download and experiment with.

Download the Example File (ConditionalFormatting.xlsx)

This Article (bookmarks):

  • What is Conditional Formatting?
    • How to Highlight Duplicates
    • How to add Color Scales
    • How to add Data Bars in Excel
    • Highlight Overdue Dates
    • How to add Icon Sets in Excel
  • How to View and Edit Conditional Formatting Rules
  • Rule Order Matters
  • How to create an In-Cell Progress Bar
  • How to Highlight Every Other Row
  • Conditional Formatting Based on Another Cell
  • How to create a Formula Rule
    • How to Highlight an Entire Row
    • How to Highlight Based on a Range
    • How to Highlight Values NOT in a Range
  • Create a Gantt Chart
  • Use Data Bars to Compare Two Groups
  • Control Scaling by Linking Min/Max to Cells
  • Change Number Formatting with CF Rules
    • Change Date Formats to d/m/yyyy
    • Hide Zero Values
    • Automatic Indenting
    • Display 23K, 23M, 23B Based on Value
    • Display Custom Icons
  • How to Copy Conditional Formatting
  • Conditional Formatting is Volatile

What is Conditional Formatting?

How to Apply Conditional Formatting in Excel

Conditional Formatting in a spreadsheet allows you to change the format of a cell (font color, background color, border, etc.) based on the value in a cell or range of cells, or based on whether a formula rule returns TRUE.

To Apply Conditional Formatting in Excel: First, select the cells you want to format. Then, go to Home > Conditional Formatting and select an option from the built in menu, or click on Manage Rules.

To Apply Conditional Formatting in Google Sheets: First, select the cells you want to format. Then, go to Format > Conditional Formatting and click on «Add another rule» in the side panel.

NOTE Google Sheets currently provides fewer conditional formatting options and controls than Excel (for example, no data bars or icon sets). The focus of this article will be on how to use conditional formatting in Excel, but many of the techniques will apply just as readily to Google Sheets.

Here are a few things you can do with the built-in options in Excel:

1. How to Highlight Duplicates

Conditional Formatting Example: Highlight Duplicates

Select your range of cells, then go to Home > Conditional Formatting > Highlight Cells Rules > Duplicates.

After viewing the duplicates, you can decide whether you need to remove them manually or use the built-in tool via Data > Data Tools > Remove Duplicates.

Highlighting duplicates in Google Sheets requires using a custom formula rule such as =COUNTIF(A:A,A1)>1 to highlight the duplicates in column A.

2. How to add Color Scales

Conditional Formatting Example: Color Scales

Select your range of cells, then go to Home > Conditional Formatting > Color Scales and pick the color range that makes sense (usually, green=good and red=bad).

Color Scales are very useful for seeing high and low values within a large data set. Color Scales can also be used to create heat maps, like this Calendar Heat Map Chart:

Calendar Heat Map Chart

3. How to add Data Bars in Excel

Conditional Formatting Example: Data Bars

Select your range of cells, then go to Home > Conditional Formatting > Data Bars and select the style you want.

Data Bars let you create horizontal bar charts and progress bars directly within a group of cells. In the example on the right, I’m using data bars to show a histogram of class grades.

The default settings for Data Bars scale the bars automatically based on the values in the Applies To range. You can control the scale used for the bars by editing the rule’s settings. I’ll be showing a couple examples of that later in this article.

4. How to Highlight Overdue Dates

Conditionally Format Overdue Dates - Calibration Log Example

To highlight overdue dates:

  1. Select the range of dates and go to Home > Conditional Formatting > Highlight Cells Rules > Less Than…
  2. Enter =TODAY()+30 to highlight dates earlier than 30 days from now. Enter =TODAY() to highlight dates earlier than today.
  3. Choose a format option from the drop-down box, then click on OK.

Conditional Formatting to Highlight Overdue Dates

Examples of this technique can be found in the Equipment Calibration Log and To Do List templates.

5. How to Add Icon Sets in Excel

Conditional Formatting Example: Icon Sets

To add Icon Sets, select your data and then go to Home > Conditional Formatting > Icon Sets > and choose one of the options. You will amost always have to customize the settings for Icon Sets.

This example, based on the Checkbook Register Template, uses a green circle icon () to show when an account balance is >=$500, yellow/orange () when it is less than $500, and red () when the balance is negative.

After selecting the icon set from the built-in menu, you need to edit the rule to define these different values. To do that, select one of the cells in the Balance column, go to Home > Conditional Formatting > Rules Manager and click on Edit Rule. The image below shows the settings used in this example:

Icon Sets - Account Balance Example Settings

TIP: One of the best ways to learn how Icon Sets work is to play with all of the different drop-down options in the rule settings.

For examples of other Icon Sets, check out the Feature Comparison Template:

Feature Comparison Template - Examples of Icon Sets

How to View/Edit Conditional Formatting Rules

Vertex42 has many templates that use both simple and advanced conditional formatting techniques. If you are using a template and want to figure out how the conditional formatting works, or want to delete or change rules, you will need to know a couple of things:

1) To view the rules for selected cells, go to Home > Conditional Formatting > Rules Manager

2) To view ALL the rules in the entire worksheet, select «This Worksheet» from the drop-down at the top of the Rules Manager window.

Conditional Formatting Rules Manager

The image above shows the 5 rules used in the Task Checklist Template. The first rule changes tasks to gray strike-through when the Done column has a check mark. The next 3 rules highlight specific text in the Priority column. The last rule adds a Progress Bar in the % Complete column.

Conditional Formatting - Task Checklist Example

I will be using this template to demonstrate some techniques and key facts about conditional formatting, so I would recommend that you download it and experiment with it as you continue to read.

Rule Order Matters

The Task Checklist Template mentioned above demonstrates two key points about rule order or heirarchy.

Key Points

  1. Conditional formatting rules are evaluated one at a time starting with the rule listed at the top.
  2. A later rule cannot override the formatting already modified by a preceding rule.

Here is the list of rules again:

The 5 Rules Used in the Task Checklist Template

Key Point #2 means that if the first rule has already changed the font color to gray, the following rules cannot change the font color to green, yellow, or red. It’s first come, first serve.

In Excel, the font color and fill color (and border, and font style, and …) can be affected independently by different rules. This means that you can have one rule that changes a font to gray, a different rule that changes the cell color to red, and a different rule that adds a data bar.

Why do I need to check the Stop-If-True box?

With the Stop-If-True box checked, none of the following rules will be evaluated if the condition of that first rule is met.

That is why the first task row doesn’t show a Data Bar in the %Complete column and why the Priority «HIGH» is not highlighted red.

What would happen if I didn’t check the Stop-If-True box? Go ahead and try it … or look at the next image.

Conditional Format Example, Stop-if-True Not CheckedResult when Stop-if-True is Not Checked

Notice how the red fill color is applied to the HIGH cell. The first rule does not define a fill color, but it does change the font color. That means that the 4th rule can change the fill color to light red, but it can’t override the font color.

Excel vs. Google Sheets: In Excel, the Number Format, Font Color, Font Style, Font Underline, Font Effects, Fill Color, Fill Effects, Border Color, Border Style, Data Bars, and Icon Sets can be affected independently by different rules. That isn’t the case in Google Sheets. In Google Sheets, conditional formatting behaves as though all rules are Stop-If-True. Excel is much more flexible and powerful in that respect.

How to Create an In-Cell Progress Bar

Create a Progress Bar Using Conditional Formatting

You’ve already seen how to add a Data Bar, so using a Data Bar for showing progress based on a percentage is as simple as making a few changes to the Data Bar settings.

To see how it works in the Task Checklist template, go to Home > Conditional Formatting > Manage Rules, click on the Data Bar rule, then click on the Edit Rule button.

Conditional Format Settings for a Progress Bar in Excel

The progress should be a value between 0% and 100%. When you create a progress bar, you need to change the Minimum value to Type:Number & Value:0, and change the Maximum to Type:Number & Value:1.

NOTE Google Sheets currently doesn’t provide an in-cell data bar option. But, you can mimic the effect using the formula =REPT(«█»,ROUND(percent*10,0)).

I’ve attempted to figure out a way to change the color of the data bars conditionally, but the best I’ve been able to come up with instead is to use a 3-color scale in addition to a gray data bar. This can help if you want to use the color to signal an incomplete task.

Conditional Data Bars Using 3-Color Scale

How to Highlight Every Other Row Using a Formula

Conditional Format Example To Highlight Every Other Row

Highlighting every other row can help make tables more readable like in the expense tracking example. To do this in Excel (without needing the Tables feature), you can create a formula-based conditional formatting rule.

Highlight Every Other Row Using Conditional Formatting

  1. Select the cells you want to format (except the header).
  2. Go to Home > Conditional Formatting > New Rule.
  3. Select «Use a formula to determine which cells to format.»
  4. Enter the formula =MOD(ROW(),2)=0.
  5. Click on Format then select a color in the Fill tab.

Likewise, to highlight every other column, you could use the formula =MOD(COLUMN(),2)=0.

This technique allows you to insert and copy/paste rows without having to update the background colors manually, but it has one major drawback: conditional formatting overrides manual formatting.

Key Point: Conditional formatting overrides manual formatting.

This means that if you want to change the fill color of a cell in your table, but the conditional formatting rule is already changing the fill color, you won’t see the change that you are making. You ARE editing the fill color, but you won’t see the change because conditional formatting is overriding your format.

If you want to manually change the fill colors in your table AND highlight every other row, you may need to use the Format as a Table feature in Excel.

NOTE Google Sheets has a feature listed right underneath Conditional Formatting called Alternate Colors. This works separate from conditional formatting and DOES NOT override custom formatting! I LOVE that!

Conditional Formatting Based on Another Cell

To change the format of a cell based on another cell, or based on a range of cells, use a formula rule to determine which cells to format. Formulas can be simple or very complex. You can use most of the standard spreadsheet functions such as IF(), AND(), MATCH(), SEARCH(), COUNTIF(), SUMIF(), etc.

How to Create a Formula Rule

How to Create a Formula-Based Conditional Formatting Rule in Excel

To create a formula rule, select «Use a formula to determine which cells to format» after clicking on New Rule from the Conditional Formatting menu or from within the Rule Manager.

A formula rule is activated when the formula returns TRUE.

For example, =G27<TODAY() will apply the format when the date in cell G27 is overdue (less than today’s date).

To format based on multiple conditions, use the AND() function in your formula. For example, =AND(A1>10,A1<20) will apply a format when cell A1 is between 10 and 20.

Formula Rules can be very tricky! When using relative references (references without dollar signs in front of the column letter or row number), you need to write your formula based on the top-left cell in the Applies To range. When you are creating the rule for the first time, write your formula based on the top-left cell that you have selected.

IMPORTANT: Always write the formula based on the top-left cell in the Applies To range!

How to Highlight an Entire Row

The Work Breakdown Structure template shows an example of highlighting an entire row when the value in the Level column is equal to 1.

How to Highlight an Entire Row Based on One Cell

The formula we are using is =($B6=1), and this applies to all the cells in the range $B$6:$G$30. One formula to rule them all! But how does it work?

Behind the scenes, Excel is essentially copying this formula to each of the cells in the Applies To range. When a formula is copied, relative references (no dollar sign) will change. This means that for cell C15, the formula would become =($B15=1). Column B stays the same (because of the dollar sign in front of the B), but the row changes.

Key Point: In Conditional Formatting Rules, absolute references stay the same ($B$1) and relative references (A1) change as Excel applies the formula to each cell in the Applies To range.

If you aren’t familiar with how absolute and relative references work, you may want to learn more about that. It’s absolutely critical for understanding formula-based conditional formatting.

How to Highlight Cells Based on a Range

You can use the MATCH() function within a conditional formatting formula rule to highlight cells whose values are found in another range or list.

For example, in the Yearly Event Calendar, dates are highlighted in the calendar if the date is found in the list of holidays, as shown in the image below.

Conditional Formatting Based on a Range of Dates

The formula is =MATCH(this_date,date_range,0) where this_date is A10 (a relative reference to the top-left cell in the Applies To range), and date_range is $Y$9:$Y$300 (an absolute reference to the list of holidays in column Y).

The MATCH formula only returns TRUE if it finds this_date within date_range. (See VLOOKUP and INDEX-MATCH Examples to learn about lookup formulas).

How to Highlight Values NOT in a Range

In some spreadsheets, I use conditional formatting to highlight values that are NOT within another range. Along with Data Validation, this can help with error checking.

The formula for the rule is =ISERROR(MATCH(this_cell,other_range,0)). This returns TRUE when MATCH does not find this_cell within other_range.

I’ve used this technique in my original Money Management Template to verify budget categories.

How to Use Conditional Formatting to Create a Gantt Chart

Watch the new Video Series: How to Make a Gantt Chart in Excel!

Most of my Gantt Chart Templates use a combination of many conditional formatting rules. The example below (from the Simple Gantt Chart) demonstrates (1) how to create the bars that show the date range for each task and (2) how to show the current date using a red border.

How to Use Conditional Formatting to Create a Gantt Chart

Rule 1 uses the formula =AND(task_end>=G$5,task_start<G$5+1) where task_end is a relative named range defined as $D7 and task_start is a relative named range defined as $C7. Using named ranges isn’t necessary. The formula could be written as =AND($D7>=G$5,$C7<G$5+1)

Rule 2 can use the same formula, with today’s date in place of both task_end and task_start. Or, the rule could be as simple as =G$5=TODAY().

The proper use of absolute and relative ranges is absolutely critical here. So, pay special attention to the placement of the dollar signs.

Note You may notice that row 7 is hidden in the screenshot. The reason for hiding the first row of the gantt chart is so that if a person inserts a row above row 8, it will use the formatting from row 7 rather than the formatting from row 6.

Using a «No-Format Stop» Rule

In some of my Gantt charts, such as the Construction Schedule, the user can pick the color of each bar. Each different color requires a separate conditional formatting rule.

One way to do this would be to add the color condition to each rule like this: =AND($D7=»red»,task_end>=G$5,task_start<G$5+1).

However, I often prefer to use what I call a «No-Format Stop» Rule. Instead of saying where you want the color to be applied, this rule defines where the color should NOT be, and stops if true.

Using a No-Format Rule for Advanced Conditional Formatting Logic

This No-Format Stop rule can be as simple as adding NOT() around the main gantt chart rule like this =NOT(AND(task_end>=G$5,task_start<G$5+1)). It’s called a «No-Format» rule because no formatting is applied. Its only purpose is to prevent the rules that come after it from being applied.

The following rules then need to only check for what color to assign. In the example, the color is entered in column D. When cell D7 is blank, the bar will be gray. When D7=»B», the bar will be blue … and so on.

Use Data Bars to Compare Two Groups

Charts like the population example below are popular for comparing two different groups.

Data Bars for Comparing Male and Female Population

The trick to creating a chart like this with Data Bars is to use two different columns. The settings for the Male column use the «Right-to-Left» direction as shown in the image below.

Settings for Data Bar Comparisons

!!! The column widths and the Min/Max values need to be identical for both columns of data, or the visual display will misrepresent the numbers. In this case, the Minimum is 0 and the Maximum is 25 for both the blue data bars and the red data bars.

You could argue that this type of graph is not ideal for making exact comparisons between the Male and Female population. For example, if the numbers weren’t included in the chart, could you tell that for Age 40 to 49 there were more females (20.48 vs. 20.14)? No, you couldn’t. The bars look like they are the same length.

Our brains make better length comparisons when two things are aligned and parallel. The next chart uses Data Bars arranged a little differently. Now you CAN see the difference between the Male and Female population.

Data Bars for Comparing Male and Female Population - Better

Control Scaling by Linking Min/Max to Cells

A great solution for controlling the scaling for Data Bars and Color Scales is to link the Minimum and Maximum values to cells that you can edit. Using this approach, you can have different rules using the same Min/Max values. Here’s an example:

Animation - Data Bars Scale Linked to Cells

To do this, edit the rule settings with cell references like this:

Data Bars Minimum and Maximum Linked to Cells

The green data bar and blue data bars in this example are separate rules, but both rules use Min/Max values linked to cells C139 and D139.

Change Number Formats via Conditional Formatting

Some tricks I like to use in my templates involve changing the custom number format via conditional formatting based on user-selected options. If you aren’t already familiar with how to create custom number formats, I would encourage you to read the article Custom Number Formats in Excel.

Suffice it to say for now that you assign custom number formats by going to the Number tab when editing the Format for a conditional formatting rule.

Custom Number Formats via Conditional Formatting

Change Date Formats to d/m/yyyy

If you are sharing a file with people from different countries, you may want a simple way to switch the display of dates from m/d/y to d/m/y. I use this technique in Gantt Chart Template Pro.

Changing Date Formats using Conditional Formatting

The date in cell F131 displays a date as m/d/yyyy by default, but when the user selects «dmy» in cell D131, the CF rule changes the format to d/m/yyyy.

You could set up similar options to switch time formats between standard and 24-hour time, or change the display of numbers from decimal to fractions.

Note Developers: To avoid having to switch between date formats, use the built-in date formats marked with the asterisk (*) when you can. From Excel: «Date formats that begin with an asterisk (*) respond to changes in regional date and time settings that are specified for the operating system.»

Hide Zero Values

This example shows 3 different ways to hide zero values using conditional formatting.

How to Hide Zero Values using Conditional Formatting

  • The 2nd column hides the zero values by changing the font color to white.
  • The 3rd column changes the custom number format to » — «.
  • The 3rd column changes the custom number format to » «.

I personally prefer replacing zeros with a dash because otherwise the cell looks blank, and cells that look blank tend to be deleted or overwritten because you think they are empty.

Automatic Indenting

A custom number format will allow you to add text characters before or after the number, so you can simulate indenting by adding a number of spaces before your text using the format code » «@.

I use this technique in both the free Work Breakdown Structure template, and the premium Gantt Chart Template.

Automatic Indenting via Conditional Formatting

In this example, the formula is counting the number of decimal points in the WBS number. One rule adds 3 spaces before the text if it finds 1 decimal point. A second rule adds 6 spaces before the text if it finds 2 decimal points. See the article Text Manipulation Formulas to learn how this formula counts decimal places.

Display 23K, 23M, or 23B Based on the Value

Displaying large numbers as thousands, millions, or billions is VERY common, but how do you automatically display «K» or «M» or «B» depending on the value of the number? Using 3 different CF rules with the custom format codes 0.0K, 0.0M, and 0.0B.

Display Thousands, Millions, or Billions using CF Rules

Display Custom Icons

Excel has a limited number of icons available for Icon Sets. However, if you use unicode symbols and emojis, you can create your own icons using multiple CF rules. The format codes in this example are simply 0* X where X is the unicode character. To place the icon on the left with the number on the right, you could use X* 0.00 instead.

Custom Icons Using Emojis in CF Rules

Check out the Moon Phase Calendar to see how it uses conditional formatting to replace dates in a calendar with moon phase unicode characters.

Using Conditional Formatting to Display Moon Phases

How to Copy Conditional Formatting

The simple answer is that unless you tell Excel or Google Sheets NOT to, conditional formatting will be copied whenever other formatting is copied. For example, when you copy/paste cells, when you use the format painter tool, and when you insert rows and columns.

Copying conditional formatting may not always behave the way you expect it to. Sometimes that may not matter, but in other cases it may cause significant errors in how the data is interpreted. So, it’s always a good idea to check your conditional formatting rules after copying/pasting.

One of the main problems I’ve seen occurs when copying a row and inserting the copied row. Rules may be split, resulting in separate rules for different ranges when you expect there to be only one rule for the entire range. This can cause problems with color scales and data bars, especially.

To avoid the problem of splitting CF rules, when pasting you can use Paste Special and choose the «All Merging Conditional Formats» option.

Conditional Formatting is Volatile

If you use a lot of conditional formatting in your worksheet, or the rules involve inefficient formulas, you may notice Excel appear to slow down. That is because Conditional Formatting is volatile — meaning that the rules are evaluated every time the display refreshes.

To experiment with this concept, I built the following example. The fire in the display will flicker every time rules are evaluated, allowing you to test actions that cause the display to refresh.

Conditional Formatting is Volatile

Download the Example File (VolatileCF.xlsx)

Wrap Up and Final Tips

If you like this article, or use some of these ideas, please share the link to this article via your website and social media!

I didn’t talk about all the possible uses for conditional formatting, and not even some of the most common uses, such as making negative values red and highlighting based on specific text values. That is partly because many of these techniques are extremely easy to implement using the built-in options.

If you have questions, please go ahead and submit a comment below.

If you’d like to try some geeky fun, check out the Mine Blaster 1000 game. It makes use of multiple overlapping conditional formatting rules to create a game something roughly like Minesweeper (without any VBA).

Mine Blaster 1000 - Using Conditional Formatting

Spreadsheets are the go-to information hub for individuals, teams, and organizations of all sizes to store data. However, large data sets can make it difficult to identify trends, pick out key pieces of information, and track deadlines. Luckily, Microsoft Excel has a feature called conditional formatting that alleviates some of these challenges. 

Conditional formatting enables you to apply special formatting to cells in your spreadsheet that meet certain criteria. Excel has a sizable library of preset conditions that you can apply fairly simply, or you can create your own conditional formatting rules using Excel formulas. This guide will provide in-depth step-by-step examples of the most popular conditional formatting functions for basic and advanced users in Excel 2016. Then, we’ll show you how to perform the same functions in another spreadsheet application, Smartsheet.

What Is Conditional Formatting?

Conditional formatting is a feature of many spreadsheet applications that allows you to apply special formatting to cells that meet certain criteria. It is most often used to highlight, emphasize, or differentiate among data and information stored in a spreadsheet. 

Conditional formatting enables spreadsheet users to do a number of things. First and foremost, it calls attention to important data points such as deadlines, at-risk tasks, or budget items. It can also make large data sets more digestible by breaking up the wall of numbers with a visual organizational component. Finally, conditional formatting can transform your spreadsheet (that previously only stored data) into a dependable “alert” system that highlights key information and keeps you on top of your workload. 

Originally a powerful feature of Excel, other spreadsheet applications have also adopted this functionality. 

Conditional Formatting Basics

Conditional formatting consists of four main components: if-then commands, preset conditions, custom conditions, and applying multiple conditions. We’ve outlined how to use these commands and conditions to create and apply rules to your Excel spreadsheets below:

  • If-Then Logic: All conditional formatting rules are based on simple if-then logic: if X criteria is true, then Y formatting will be applied (this is often written as p → q, or if p is true, then apply q). You won’t have to hard-code any logic, though — Excel and other spreadsheet apps have built-in parameters so you can simply select the conditions you want the rules to meet. Advanced users can also apply the program’s built-in formulas to logic rules.
  • Preset Conditions: Excel has a huge library of preset rules encompassing nearly all functions that beginner users will want to apply. We’ll familiarize you with several of the most popular ones in the next section. 
  • Custom Conditions: For situations where you want to manipulate a preset condition, you can create your own rules. If appropriate, you can use Excel formulas in the rules you write.
  • Applying Multiple Conditions: You can apply multiple rules to a single cell or range of cells. However, be aware of rule hierarchy and precedence — we’ll show you how to manage stacked rules in the walkthrough.

Overall, applying conditional formatting is an easy way to keep you and your team members up to date with your data — calling visual attention to important dates and deadlines, tasks and assignments, budget constraints, and anything else you might want to highlight. When applied correctly, conditional formatting will make you more productive by reducing time spent manually combing data and making it easier to identify trends, so you can focus on the big decisions.

How to Apply Basic Conditional Formatting in Excel

You can apply conditional formatting to your Excel spreadsheets using various tools and features found within the program. This step-by-step walkthrough shows you how to apply the most commonly used formatting for highlighting, data bars, color scales, and more.

Step 1: Apply Highlight Rules to Your Excel Spreadsheet

Highlight rules apply color formatting to cells that meet specific criteria that you define. They are the most basic type of conditional formatting rule, and Excel provides a variety of preset highlight functions. 

  1. Open an existing spreadsheet in Excel, or start from scratch and manually enter new data. In this example, we’re using an inventory list that tracks the number of each item currently in stock, as well as some additional information about each product. 
     

  2. To apply highlight rules, select the range of values you want to apply a rule to. For this example, we want to highlight any product that’s quantity is less than 100 units. So, select the values in the Qty. column (C4:C26). 
  3. From the Home tab, click Conditional Formatting on the right side of the toolbar, and click Highlight Cells Rules from the dropdown menu. Click Less than
     

    Conditional formatting highlight cells rules Excel

  4. A box will appear. Type 100 in the empty field. Click OK
     

  5. Your spreadsheet will now reflect this highlight rule, with the quantities less than 100 highlighted red with red text. 

    Tip: You can change the color of the highlighted cell by clicking on the Format with: dropdown menu and selecting on another option.

    Conditional formatting first rule highlight Excel

  6. To highlight text cells, repeat step 2. This time, we want to highlight certain model types (M compatible), so we’ll select the cells in the Item name column.
  7. Click Conditional Formatting > Highlight Cells Rules > Text that Contains…
     

  8. ​Type M compatible in the text box. To differentiate from our previous highlight rule, select green fill with dark green text from the Format with: dropdown menu. Click OK
     

    Conditional formatting M compatible Excel

  9. Now, cells containing the text M compatible are highlighted.
     

    Conditional formatting changes updated Excel

Using these same steps and menu options, you can apply highlight rules to find Duplicate Values, Dates, or values that are Greater than…, Equal to…, or Between… values that you select. All of these possibilities are available through the menu options. 

Step 2: Create Top/Bottom Rules

Step 3: Apply Data Bars

Data bars apply a visual bar within each cell. The length of the bar relates the value of the cell to other cell values in the selected range. 

  1. We’ll apply data bars to the Qty. column so we can easily assess the ratios of items in stock. Click the top of the Qty. column to select this range of cells. 
  2. Click Conditional Formatting > Data Bars. You’ll see two options — one for Gradient Fill and one for Solid Fill. They function identically; just select the option and color you prefer. 
     

    Conditional formatting choose data bars Excel

  3. Your sheet will now reflect the added rule. 
     

    Conditional formatting data bars highlighted updates Excel

Step 4: Apply Color Scales

Color scales are similar to data bars in that they relate a cell’s values in a selected range. However, instead of representing this relationship by the length of a bar, color scales do so with color gradients. One color is assigned the “lowest” value and another the “highest,” with a range of colors in between. 

  1. We’ll apply color scales to our Selling price column. Click the top of column D to select this range. 
  2. Click Conditional Formatting > Color Scales. You’ll see a variety of different color ranges; select the one you want.
     

    Conditional formatting color scales Excel

  3. Your spreadsheet now shows the selling prices by color — red cells are the most expensive, and green cells are the least expensive. 
     

    Conditional formatting prices by color Excel

Step 5: Apply Icon Sets

Icon sets apply colorful icons to data. They are simply another way to call attention to important data, and relate cells to one another. 

  1. We’ll apply icon sets to the Purchase price column to show low, middle, and high priced items. Click the top of the Purchase price column to select the range of values. 
  2. Click Conditional Formatting > Icon Sets. You’ll see a variety of options for Directional, Shapes, Indicators, and Ratings icons. You can choose any of these to fit the needs of your data. In this example, we’ll choose the first Directional option: red, yellow, and green arrows that indicate high, middle, or low priced items. 
     

    Conditional formatting icon sets Excel

  3. Your sheet reflects this new formatting rule.
     

    Conditional formatting icon sets rule highlight Excel

Step 6: Edit and Delete Conditional Formatting Rules

Now you’ve learned the most common conditional formatting presets in Excel, your spreadsheet provides a lot of information at a glance. However, you might want to edit some of these rules later on, or delete them completely. 

  1. Click Conditional Formatting and select Manage Rules… from the dropdown list. 
     

    Conditional formatting manage rules Excel

  2. The Manage Rules box will appear. Click the dropdown menu at the top of the box and click This Sheet to list the conditional formatting rules you have applied to the current sheet. 
     

    Conditional formatting manage rules this sheet Excel

  3. To edit a rule, click the rule you want to change. In this example, we want to highlight the bottom ten values in the Total value of stock column, rather than the bottom five that we currently have highlighted. Click the Bottom 5 row. Then, click Edit Rule… at the bottom of the box. 
     

    Conditional formatting edit rule Excel

  4. A new box opens where you can adjust the conditions of the rule. Type 10 in the number field and click OK
     

    Conditional formatting edit formatting rule Excel

  5. Excel will bring you back to the Manage Rules box. You must click OK to save the changes you made to the original rule. 
     

    Conditional formatting rule changing highlight Excel

  6. To delete a rule, return to the Manage Rules box and choose This Sheet. Click the rule you want to delete — in this case, the color grading on Selling price. Click the — symbol (next to Edit Rule…) in the lower left hand corner. Click OK
     

    Conditional formatting delete rule Excel

  7. The conditional formatting on the Selling price column is now deleted. 
     

    Conditional formatting delete rule changes highlight Excel

You now have everything need to create basic conditional formatting using presets in Excel 2016. For more advanced functionality such as creating a new rule, using Excel formulas, and creating rules dependent on another cell, see the “Advanced” section below. 

First, we’ll look at how we can apply the same conditional formatting rules we learned in Excel to another spreadsheet program, Smartsheet. 

How to Apply Basic Conditional Formatting in Smartsheet

Use conditional formatting in Smartsheet to apply many of the same rules and effects available in Excel. We’ll guide you through every function described in the previous section, with some modifications that better align with Smartsheet features.

You can create spreadsheets in Smartsheet two ways: by manually entering data into Smartsheet, or by importing an existing spreadsheet from programs like Excel and MS Project. For this tutorial, we’ll use the same data set from the Excel tutorial, so we’ll import the original version (with no conditional formatting) from Excel. 

Step 1: Open Your Existing Excel Spreadsheet in Smartsheet

Step 2: Apply Highlight Rules

  1. ​​​​​​To highlight a cell, click the conditional formatting icon on the toolbar. 
  2. A box will appear where you can set conditional formatting rules. Click Add New Rule in the top left corner. The if-then logic is already written into the new rule, so you can simply create the conditions. 
     

    Conditional Formatting Window

  3. Click set condition. Just like in the Excel example, we want to highlight any items that are stocked below 100 units. Select Qty. from the column list on the left, select is less than from the center dropdown list, and then type 100 in the field on the right. Click OK
     

    Set Quantity Condition

  4. Now we need to apply the formatting. Click this format and a dropdown menu with formatting options appears. For this example, we’ll use a paint fill. Click the paint bucket icon and select red. 
     

    Add Quantity Condition

  5. Specify which cells should get this formatting. Smartsheet will default to format the entire row, but we only want to highlight the cells in the Qty. column. Click entire row and click Qty. from the dropdown list. Click OK
     

    Set Quantity Condition Entire Row

  6. Your conditional formatting rule is now reflected in your spreadsheet.
     

    Quantity Conditional Formatting Smartsheet

  7. To highlight text cells, repeat steps 1 and 2. Click set condition. Now, we want to highlight any M compatible items. Select Item name from the left-most list, contains from the center list, and type M compatible in the right field. Click OK
     

    Item Name Conditioning Formatting

  8. Click this format and click the paint bucket item. Select green. For this rule, we want to highlight the entire row. (Again, Smartsheet defaults to this option.) Click OK
     

    Set Item Name Conditional Formatting

  9. Your second rule is now reflected in your data set. 
     

    Item Name Conditional Formatting Smartsheet

Step 3: Apply Progress Bars (Data Bars)

In place of Excel’s Data Bars preset, you can create Progress Bars in Smartsheet. Progress Bars are a symbol that you can apply to cells to show and compare the level of completeness. In this example, we’ll apply progress bars to denote current inventory levels (from zero to 100 percent). 

  1. To create Progress Bars in Smartsheet, you first need to create a new Symbols column. Cells in a Symbols column will only hold special characters, such as progress bars. 
  2. To create a new column, right-click the Qty. column and click Insert Column Right.
     

    Insert Column Right

  3. A box will open. We’ll name this column Inventory Level, and select Symbols… from the list of column-types. In the right-hand field, scroll down and select the progress bar icon. Click OK.
     

    Add Progress Bar

  4. Click into cells in the new Inventory Level column and select the appropriate level of inventory: Empty, Quarter, Half, Three Quarter, or Full. This progress bar relates the current level (from the Qty. column) to level you need. 
     

    Set Progress Bars

  5. Here’s what your sheet will look like when all progress bars are filled in. 

    Progress Bars in Smartsheet

Tip: You can also type Empty, Quarter, Half, Three Quarter, or Full into each cell, and Smartsheet will autofill with the appropriate progress bar. 

Manually Enter Progress Status

Tip: You can also automate progress bars by using an if-then formula in Smartsheet. For more information on how to do this, check out this resource on symbol formulas.

Step 4: Apply Icon Sets

To apply icon sets in Smartsheet with conditional formatting, you’ll have to use formulas (we’ll get into that in the “Advanced” section). Instead, you can add informative icons to your data by creating a special Symbols column. 

  1. Right-click the Qty. column and click Insert Column Right
     

    Insert New Column

  2. In the box that opens, type Qty. Status in the name field. Click Symbols from the dropdown menu and choose from the library of available symbols (Flag, Priority, Decision, Status, Direction, and Measure icons). In this example, we’ll choose RYG balls in the Status section. Click OK
     

    Add Progress Symbols

  3. Now, you can update your sheet with the appropriate color status ball by adding conditional formatting as shown above. 
     

    Progress Symbols in Smartsheet

Step 5: Edit and Delete Conditional Formatting Rules

Editing and deleting conditional formatting rules in Smartsheet is extremely easy. 

  1. To edit a rule, click the Conditional Formatting icon on the toolbar to open the list of rules. Click the condition you wish to change and edit the information in the box that opens. Click OK
     

    Edit Conditional Formatting

  2. To delete a rule, click the carrot on the left side of each rule. Click Delete Rule from the dropdown menu. Click OK
     

    Delete Conditional Formatting

Tip: You can also disable a rule by clicking Disable Rule from the dropdown menu and then clicking OK. This will put the rule on “hold” without deleting it, in case you want to re-enable it later on. 

Now you know how to use conditional formatting and other colors and symbols to add formatting to your sheet in Smartsheet. In the following sections, we’ll walk you through more advanced conditional formatting functions in Excel and Smartsheet.

Advanced Conditional Formatting Functions in Excel

Once you have mastered the basics, Excel includes some additional advanced conditional formatting functions. We’ll guide you through applying stop-if-true rules, using the AND formula, setting rule hierarchies and precedence, and other unique situational formatting conditions below.

Step 1: Create a New Rule and Apply Stop if true Rule

In some instances, you might want to stop a certain condition, without deleting the entire rule. The Stop if true rule in Excel enables you to do so. 

  1. In our example, we applied an icon set of three directional arrows to the Purchase price column to indicate low, medium, and high price ranges. However, we might actually only want to call attention to the lowest cost items, as three icons can clutter the sheet (and provide more information than actually needed). 
  2. First, create a separate condition on this column. Click the Purchase price column to select these values. 
  3. Click Conditional Formatting > Manage Rules… to open the Manage Rules box. Keep the default Show formatting rules for: Current Selection from the dropdown menu, because we are only adjusting the rule on this column. 
     

    Conditional formatting current selection Excel

  4. Click the + in the bottom left corner to create a new rule. A new box opens where you can  assign conditions to the new rule. 
  5. From the Style menu, select Classic
  6. Instead of applying a different icon to bottom, middle, and top price ranges (as we currently have), we only want to show the bottom 50 percent. So, select Top from the left dropdown menu, type 50 in the middle field, and check the Percent box. 
     

    Conditional formatting percent selection excel

  7. To apply color formatting, Select Custom format from the Format with dropdown menu, and a new formatting box opens. Click the Fill tab, and click No Color.
     

    Conditional formatting no fill color Excel

  8. Next, click the Font tab, and select black text. Click OK
     

    Conditional formatting choose font color Excel

  9. Click OK again in the original New Formatting Rule box. 
  10. You’ll return to the Manage Rules box, where you now have two rules applied to the Purchase price column. Click the Stop if true box to the right of the new rule you just created. Click OK
     

    Conditional formatting stop if true Excel

  11. Your sheet will now only show the icon sets for the items with a purchase price in the bottom 50 percent. 
     

    Conditional formatting stop if true updates Excel

Step 2: Apply Multiple Conditions to a Rule with AND Formula

Adding Excel’s formulas to your conditional formatting rules is one way to elevate your logical rules. The  AND formula is one of the most popular, easy-to-use formulas. It lets you add multiple conditions within a single rule, rather than writing out each rule separately. To format cells they must meet both conditions.

  1. We’ll create a new rule to highlight any cell in the Item # column that contains both a B and an L. Click the top of the Item # column to select this range of cells. 
  2. Click Conditional Formatting > New Rule
  3. In the dialogue box, select Classic from the top dropdown list. Select Use a formula to determine which cells to format, since we’re using a formula. 
  4. We want to search cells in the Item # column for a B and L, and highlight that cell when both conditions are true. To do this, we’ll use Excel’s ISNUMBER and SEARCH formulas, with the AND formula, to look for the B and L values. 
  5. =AND(ISNUMBER(SEARCH(«B»,A1)),ISNUMBER(SEARCH(«L»,A1)))
     

    Conditional formatting edit formatting rule classic Excel

  6. Click OK. Your sheet will highlight all cells in Item # that meet both of these conditions. 
     

    Conditional formatting both conditions met Excel

Tip: Understanding the formula: 

  • We use AND at the beginning of the formula to show that both of the following conditions must be met in order to apply the conditional formatting.
  • The basic syntax of the nested formula is ISNUMBER(SEARCH(“substring”,text)) where “substring” is the character(s) you are looking for, and “text” is the cell(s) you want to search. 
  • We are searching for two separate conditions, so we write the ISNUMBER(SEARCH(“substring”,text)) formula twice, separated by a comma. 

This example is just one of hundreds of different formulas you could enter with the AND function. For more information on using Excel formulas with conditional formatting, click here.

Step 3: Conditional Formatting Based on Another Cell

You can also create rules to highlight certain cells based on the value of another cell. 

  1. In this example, we’ll create a “quantity threshold” — items with inventory level below this threshold will be considered “at risk.” We already have a rule that highlights cells in the Qty. column under 100. However, that threshold might change over time, depending on manufacturing or selling rates. So, we want to create a highlight rule that is dependent upon a threshold that we set.
  2. To the right of your data, create a box for Quantity Threshold and choose an amount. In this example, we use 200. (Note the cell you type the amount in. Here, it’s I5.)
     

    Conditional formatting quantity threshold Excel

  3. Create a new rule by clicking Conditional Formatting > New Rule
  4. In the dialogue box, click Classic and Use a formula to determine which cells to format from the dropdown menus. 
  5. In the formula field, type =C4<$I$5 and keep the default formatting. Click OK
     

    Conditional formatting edit formatting rule edit formula Excel

  6. Numbers in the Qty. column that are less than the Quantity Threshold in I5 (200) will now be highlighted. 
  7. Now, you’ve created a dynamic rule. This means that as your threshold changes, the rule will still be applied to the Qty. column and the formatting will adjust as appropriate. 

Tip: Understanding the formula:

  • In this formula, we are simply testing whether or not values in column C are less than the value in I5. 
  • Start with “=C4” to tell Excel where we want to start evaluating values from. 
  • Use ‘$’ symbol around I because it’s an absolute value — we are only evaluating cells in column C against this single cell. 

Step 4: Data Validation and Dropdown Lists

While data validation is not technically monitored through conditional formatting rules, you can use it to a similar effect: controlling the formatting of your sheet. You can apply data validation to ensure that any cell-type only allows certain entries (text or numbers only, text length, etc.). In this example, we’ll show you how to create a dropdown list and validate data only from that dropdown list. 

  1. We’ll create an additional column of which employee last updated the sheet, and create a dropdown list to choose from. First, click where you want to add the column on the sheet. Create a new column by clicking Insert > Insert Sheet Columns from the ribbon on the Home tab. 
     

    Conditional formatting insert_sheet_column

  2. We’ll name this column Updated By
  3. Now we need to make a list of employees, that the dropdown list will later pull from. Create a second sheet (in the same Excel workbook) by clicking the + sign on the tab at the bottom of the spreadsheet, and write a list of employee names in column B.
     

    Conditional formatting second sheet Excel

  4. Select the range of data (all the names) you want to include in your list. Make this list into a table by clicking the Insert tab > Table
  5. The dialogue box will show the range of data you selected for the table. Click My table has headers, since we began the list with Employees. Click OK.
     

    Conditional formatting create table Excel

  6. Now we have to name this list so that Sheet 1 can pull from it. Click Formulas tab  > Define Name on the ribbon. 
     

    Conditional formatting verify name Excel

  7. In the dialogue box, type the name of the list. We’ll call it Employees. Double check that the selected range is still correct. Click OK
     

    Conditional formatting verify name Excel

  8. Go back to Sheet 1. Now, we have to make the Updated By column into a dropdown list. We’ll use the data validation function to do this. 
  9. Select the Updated By column to apply data validation to this range of cells.
  10. Click the Data tab on the ribbon and click Data Validation > Data Validation…
     

    Conditional formatting data validation Excel

  11. In the dialogue box, choose List from the dropdown menu to restrict data entered in this range to a list. Type =Employees in the Source field, since we’re pulling from the list we just created (in Sheet 2). Click OK.
     

    Conditional formatting data validation source Excel

  12. There is now a dropdown list in the Updated By column. Your sheet will only accept data in this column that comes from the Employees list on Sheet 2. 
     

    Conditional formatting choose value for updated by column Excel

  13. You can now fill in the column by selecting a name from the dropdown list. 
     

    Conditional formatting updated by column highlight Excel

Step 5: Rule Hierarchy and Precedence

As you accumulate conditional formatting rules, watch out for rule hierarchy. Since you can apply multiple conditions to a cell (or row), they occasionally conflict. When this happens, Excel has default precedence rules that may cause one rule to override another, so you can lose your formatting. To combat this, you can change the hierarchy of the rules. 

Adjusting rule hierarchy in Excel is straightforward, but you should also understand the logic behind rule precedence:

  • Newer rules will always assume precedence over older rules. This means that the precedence of your rules will be in the reverse order of how you created them.
  • When multiple rules evaluate as true to a cell, they may or may not conflict. Applying multiple rules to a cell does not necessarily mean that they will interfere. 
  • Rules don’t conflict if they are changing different things about the cell. For instance, if one rule changes text color and another changes fill color both rules should co-exist in the cell. 
  • Rules conflict when the outcomes are the same. For instance, if one rule changes a font color to green and another changes the font color to blue the newer rule takes precedence.

To adjust rule hierarchy in Excel, follow these steps:

  1. All rule hierarchy is controlled through the Rule Manager in Excel. 
  2. From the Home tab, click Conditional Formatting > Manage Rules… to open the Rule Manager. 
  3. Select This Sheet from the top dropdown list to pull up all lists applied to the current sheet. 
  4. To change the order (hierarchy) of rules, select a rule and click the up and down arrows in the top right corner to move it. Click OK. Remember the rule closest to the top will take precedence.
     

    Conditional formatting change rules hierarchy Excel

Advanced Conditional Formatting in Smartsheet

Many advanced Excel conditional formatting options are available to Smartsheet users, as well. We’ll teach you how to apply stop-if-true rules, create rules with multiple conditions, create formatting rules based on other cells, and set rule hierarchies and precedence.

Step 1: Add New Rule and Apply Stop If True Function

Adding a new rule in Smartsheet is easy (you already learned how in the “Basic” section). Now, we’ll apply the same “stop if true” logic from Excel in Smartsheet. 

  1. Add a new rule by clicking the conditional formatting icon on the toolbar. Click Add New Rule and click Set condition.
  2. For this rule, we want to call attention to the shipment order dates that are after 06/20/30. The easiest way to do this is to apply the same logic as “stop if true” in Excel. 
  3. Click Shipment Order Date in the left field to set a condition in this column. 
  4. Instead of defining criteria (as we have been doing), click select from a list. The list of values in the Shipment Order Date column appear. 
     

    If True Function

     

  5. Click 06/20/30. Then, because we want to highlight all the dates that are not this date, check the Apply format when this condition is NOT met box. (This functions just like the “stop if true” box in Excel.) Click OK
     

    Apply Format When Condition Not Met

  6. Click this format and apply whatever format you want. We’ll make the text bold. 
  7. Click entire row and select the Shipment Order Date column. Click OK
     

    Shipment Order Date Condition

     

  8. Now, all dates other than 07/01/15 will be bolded in the Shipment Order Date column.
     

    If Then Shipment Order Date

Step 2: Add Multiple Conditions to a Rule

Just like in Excel, you can use Smartsheet’s built-in formulas when creating conditional formatting rules. However, Smartsheet makes it easy to perform some of the simple functions that basic Excel formulas provide, so you don’t have to worry about remembering complicated formula syntax. To perform the AND function, you can simply click to add multiple conditions to any conditional formatting rule.

  1. Click the conditional formatting icon on the toolbar and click Add New Rule
  2. Click set condition. We want to highlight cells in the Item # list that contain both a ‘B’ and an ‘L.’ Click Item # from the dropdown list on the left.  
  3. For the conditions, select contains and type B. Click into the second prompted condition and type L to create the second condition. (This will perform the AND function.) Click OK.

    Multiple Conditions Rule

  4. Apply the formatting to your rule. We’ll use a yellow fill. 
  5. Change entire row to Item #. Click OK
     

    Item Number Multiple Conditions

  6. Your sheet will now highlight those values in Item # that contain both a B and an L.
     

    Multiple Conditions Smartsheet

You can still use formulas with conditional formatting, if you’d like. For an introduction on how to use formulas, check out this resource.

Step 3: Conditional Formatting Based on Another Cell

Smartsheet also makes it easy to apply conditional formatting based on another cell. Instead of using complicated formulas to reference different cells, you can simply control which cells to pull from and format with a few clicks. 

  1. In this example, we want to highlight the Item Name column if the status bar is red, to call attention to at-risk items. To do this, we’ll create a rule that pulls from the Qty. Status column, but applies formatting to the Item Name column. 
  2. Click the conditional formatting icon on the toolbar and click Add New Rule > set condition.
  3. Click Qty. Status from the drop down list and click Red. Click OK.
     

    Quantity Status Red

  4. Apply a light red paint fill to format with.
  5. Click entire row and select Item name. This will apply formatting to cells in the Item name column, even though we’re pulling information from the Qty. Status column. 
     

    Quantity Status Item Name

  6. Click your new rule and drag it to the top of your rules list. Since we have multiple highlighting rules, this will ensure that this rule takes precedence over others.
     

    Drag Rule to Top

     

  7. Cells in Item Name will now be highlighted if the Qty. Status ball is red. 
     

    Conditional Formatting Hierarcy

Tip: To eliminate visual redundancy, you can hide the Qty. Status column in your sheet. Simply right-click the column and click Hide column. Your sheet will retain its formatting based on that column, but it will look cleaner. 

Hide Column Smartsheet

Step 4: Rule Hierarchy and Precedence

Managing rule hierarchy is quite simple in Smartsheet. The rules also interact the same way as Excel (you can apply multiple rules to a single cell, but only one will show up if there’s a conflict). However, the default precedence is a little different:

  1. Click on the conditional formatting icon to bring up the rules. 
  2. In Smartsheet, rules higher on this list have precedence. So, the rules have descending hierarchy from the top to bottom of the list. 
  3. To change hierarchy, simply click on a rule and drag it up or down.
     

    conditional formatting rule precedence Smartsheet

Frequently Asked Questions About Conditional Formatting

The most commonly asked questions about conditional formatting include queries about who can make changes, where to learn about using formulas, and how to copy conditional formatting rules between sheets. We’ve answered these and other frequently asked questions below: 

Will conditional formatting change the values in my cells?

No. Conditional formatting only applies formatting to your cells. However, you can use conditional formatting to manipulate the values in your cells by using formulas, or by creating rules that change the value of a cell based on another cell.  

Can anyone change or apply conditional formatting to the spreadsheets?

Only one person can update conditional formatting rules in Excel at a time. In Smartsheet, any collaborator with Admin permissions can create or edit conditional formatting, but editors and viewers cannot. Click the Sharing button to adjust permissions.

Does the Office 365 (cloud) version of Excel support conditional formatting?

Users can only view conditional formatting in the cloud version of Excel. To add or edit rules, download the Office 365 desktop version. Be careful of version control issues when working with Office 365. 

I’m not comfortable using Excel formulas. Where can I learn more?

Here is a list of common questions for using Excel formulas with conditional formatting. For a comprehensive list of all Excel formulas, click here. For help with using formulas with conditional formatting in Smartsheet, check out these tips. 

How do I add conditional formatting to a new document in Excel?

To copy conditional formatting to a new workbook or sheet, select the cells you want to copy conditional formatting from, and click the Format Paint icon. Drag your cursor over the column, rows, or document to apply the rules. 

Here’s a walkthrough of this function.

Keep Your Team in Sync with Real Time Conditional Formatting in Smartsheet

Empower your people to go above and beyond with a flexible platform designed to match the needs of your team — and adapt as those needs change. 

The Smartsheet platform makes it easy to plan, capture, manage, and report on work from anywhere, helping your team be more effective and get more done. Report on key metrics and get real-time visibility into work as it happens with roll-up reports, dashboards, and automated workflows built to keep your team connected and informed. 

When teams have clarity into the work getting done, there’s no telling how much more they can accomplish in the same amount of time. Try Smartsheet for free, today.

Понравилась статья? Поделить с друзьями:
  • Excel conditional formatting for table
  • Excel conditional formatting and rule
  • Excel conditional format of row
  • Excel conditional format formula if
  • Excel conditional cell format