Suppose you want to color cells B1:B10
if their values ββare not equal to the values A1:A10
, i.e.
B1<>A1
leads to the color B1
, B2<>A2
leads to the color B2
, etc.
Then you can do the following
Range columnBRange = (Range)oSheet.Range[oSheet.Cells[1,2], oSheet.Cells[10,2]]; Range columnARange = (Range)oSheet.Range[oSheet.Cells[1,1], oSheet.Cells[1,1]]; FormatCondition cond = (FormatCondition) ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "="+ColumnARange.Address[false,true]); cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); //Red letters cond.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow); //Light yellow cell background
Note that you need to add from "="
to ColumnARange.Address[false,true]
, because otherwise the Add
method uses Address
as a literal string instead of a cell reference.
If you look at the conditional formatting rule that applies to cells B1:B10
in an Excel worksheet, it will indicate Cell Value <> B1
for each cell in the range that confuses IMO a bit, but formatting is applied nevertheless.
For completeness: I use optional objects in the Range.Address
property, for example, Range.Address[isRowAbsolute,isColumnAbsolute]
source share