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 based on the Text in the Cell

  • 2 min to read

This example demonstrates how to create a rule that applies a conditional format based on the text in a cell.

  1. To create a new conditional formatting rule represented by the TextConditionalFormatting object, access the collection of conditional formats from the Worksheet.ConditionalFormattings property and call the ConditionalFormattingCollection.AddTextConditionalFormatting 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 ConditionalFormattingTextCondition enumeration values.
    • A text string to be highlighted in a range of cells.
  2. Specify formatting options to be applied to cells if the condition is true using the ISupportsFormatting.Formatting property of the TextConditionalFormatting object.

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

// Create the rule to highlight values with the given text string in cells A2 through A15.
TextConditionalFormatting cfRule = worksheet.ConditionalFormattings.AddTextConditionalFormatting(worksheet["$A$2:$A$15"], ConditionalFormattingTextCondition.Contains, "Bradbury");
// Specify formatting options to be applied to cells if the condition is true.
// Set the background color to pink.
cfRule.Formatting.Fill.BackgroundColor = Color.FromArgb(255, 0xE1, 0x95, 0xC2);

The image below shows the result (the workbook is opened in Microsoft® Excel®). In the list of authors, the name "Ray Bradbury" is highlighted in pink.

TextConditionalFormatting