How to: Format Cells Using a Two-Color Scale
- 2 minutes to read
This example demonstrates how to apply a two-color scale conditional formatting rule.
- First of all, specify the minimum and maximum thresholds of a range using the ConditionalFormattingCollection.CreateValue method that creates an instance of the ConditionalFormattingValue object. This object provides access to threshold values and their types. The type of the threshold value is determined by one of the ConditionalFormattingValueType enumeration values and can be a number, percent, formula, or percentile. Call the ConditionalFormattingCollection.CreateValue method with the ConditionalFormattingValueType.MinMax parameter to set the minimum and maximum thresholds to the lowest and highest values in a range of cells, respectively.
To apply a conditional formatting rule represented by the ColorScale2ConditionalFormatting object, access the collection of conditional formats from the Worksheet.ConditionalFormattings property and call the ConditionalFormattingCollection.AddColorScale2ConditionalFormatting method with the following parameters:
- A CellRange object that defines a range of cells to which the rule is applied.
- A minimum threshold specified by the ConditionalFormattingValue object.
- A color corresponding to the minimum value in a range of cells.
- A maximum threshold specified by the ConditionalFormattingValue object.
- A color corresponding to the maximum value in a range of cells.
Dim conditionalFormattings As ConditionalFormattingCollection = worksheet.ConditionalFormattings ' Set the minimum threshold to the lowest value in the range of cells. Dim minPoint As ConditionalFormattingValue = conditionalFormattings.CreateValue(ConditionalFormattingValueType.MinMax) ' Set the maximum threshold to the highest value in the range of cells. Dim maxPoint As ConditionalFormattingValue = conditionalFormattings.CreateValue(ConditionalFormattingValueType.MinMax) ' Create the two-color scale rule to differentiate low and high values in cells C2 through D15. Blue represents the lower values and yellow represents the higher values. Dim cfRule As ColorScale2ConditionalFormatting = conditionalFormattings.AddColorScale2ConditionalFormatting(worksheet.Range("$C$2:$D$15"), minPoint, Color.FromArgb(255, &H9D, &HE9, &HFA), maxPoint, Color.FromArgb(255, &HFF, &HF6, &HA9))