以编程方式使用条件格式在Excel工作表中查找重复的值

我需要在Excel工作表中使用条件格式编程方式查找重复的值。

试过这种方式,但在6行代码我有COMexception

不能转换为Excel.FormatCondition

这是我的代码

Excel.Workbook xlWB = Application.ActiveWorkbook; Excel.Worksheet xlWS = xlWB.ActiveSheet; xlWS.Range["B2:B9"].Select(); Excel.Range xlS = Application.Selection; xlS.FormatConditions.AddUniqueValues(); Excel.FormatCondition xlFC = (Excel.FormatCondition)xlS.FormatConditions[xlS.FormatConditions.Count]; xlFC.SetFirstPriority(); Excel.FormatCondition xlFC1 = (Excel.FormatCondition)xlS.FormatConditions[1]; xlFC1.Interior.Pattern = Excel.XlPattern.xlPatternAutomatic; xlFC1.Interior.TintAndShade = 0; xlFC1.Interior.Color = ColorTranslator.FromOle(13551615); 

看看它的MSDN链接

或者你可以使用这样的东西

  Excel.Range usedRange = Worksheet.UsedRange; usedRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); FormatCondition format = (FormatCondition)(Worksheet.get_Range("A1:D13", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, XlFormatConditionOperator.xlEqual, "=$A1=$D1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)); format.Font.Bold = true; format.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);//Duplicate values 

希望这有助于..他为我工作