The requested page is not available for the requested platform. You are viewing the content for .NET Framework 4.5.2+ platform.

How to: Format Cells that are Less than, Greater than or Equal to a Value

  • 2 min to read

This example demonstrates how to create the rule that uses a relational operator as a formatting criteria.

  1. To create a new conditional formatting rule represented by the ExpressionConditionalFormatting object, access the collection of conditional formats from the Worksheet.ConditionalFormattings property and call the ConditionalFormattingCollection.AddExpressionConditionalFormatting method. Pass the following parameters:

    • A CellRange object that defines a range of cells to which the rule is applied.
    • A condition specified by one of the ConditionalFormattingExpressionCondition enumeration values.
    • A string that specifies the threshold value. Notice that the string can determine a formula to evaluate the threshold.
  2. Specify formatting options to be applied to cells if the condition is true, using the ISupportsFormatting.Formatting property of the ExpressionConditionalFormatting object. Set the background and font colors.

To remove the ExpressionConditionalFormatting object, use the ConditionalFormattingCollection.Remove, ConditionalFormattingCollection.RemoveAt or ConditionalFormattingCollection.Clear methods.

// Create the rule to identify values that are above the average in cells F2 through F15.
ExpressionConditionalFormatting cfRule =
worksheet.ConditionalFormattings.AddExpressionConditionalFormatting(worksheet["$F$2:$F$15"], ConditionalFormattingExpressionCondition.GreaterThan, "=AVERAGE($F$2:$F$15)");
// Specify formatting options to be applied to cells if the condition is true.
// Set the background color to yellow.
cfRule.Formatting.Fill.BackgroundColor = Color.FromArgb(255, 0xFA, 0xF7, 0xAA);
// Set the font color to red.
cfRule.Formatting.Font.Color = Color.Red;

The image below shows the result (the workbook is opened in Microsoft® Excel®). Price values above the average are highlighted in yellow with red font.

ExpressionConditionalFormatting