【问题标题】:Find duplicate values in excel worksheet using conditional formatting programmatically以编程方式使用条件格式在 Excel 工作表中查找重复值
【发布时间】:2013-01-11 10:37:25
【问题描述】:

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

试过这种方式,但在 6 行代码中我得到了 COM 异常

无法转换为 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);

【问题讨论】:

  • 您将如何在 excel 中手动执行此操作?

标签: c# excel formatting conditional


【解决方案1】:

看看MSDN Link

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

 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

希望这会有所帮助..它对我有用

【讨论】:

  • 感谢您的回复。我已经检查了您提供的链接,但它对我不起作用(它会引发 COM 异常)。您提供的解决方案非常有用,但它并没有解决我的问题。我仍然不知道如何突出显示 A1:A10 范围内的重复值。
  • 这里抛出:“var xlFC = xlS.FormatConditions[xlS.FormatConditions.Count];”
  • 我尝试转换:var xlFC = (Excel.FormatCondition)xlS.FormatConditions[xlS.FormatConditions.Count];还尝试声明 Excel.FormatCondition 而不是 var.. 但它会引发 COM 异常。
  • 请参考我写的代码sn -p。 ("A1:D13") 是我工作表的 excel 范围,因此请确保您从工作表中传递了正确的范围。它将范围完全涂成黄色,它选择唯一值并将其涂成红色。
  • 感谢您的宝贵时间。但我需要绘制不唯一的重复值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2011-01-05
  • 2013-02-02
相关资源
最近更新 更多