突出显示单元格规则文本包含

时间:2013-09-23 13:46:14

标签: c# excel interop

我有以下函数= AND(EXACT(B3; F3); EXACT(F3; J3))返回TRUE或FALSE。 我想创建一个单元格规则,用于将红色着色为虚假,绿色为真值。 试图使用以下代码,但不能正常工作,我做错了什么?

   Excel.FormatConditions fcs = xlWorkSheet.Cells[i,"M"].FormatConditions;
                    Excel.FormatCondition fc = (Excel.FormatCondition)fcs.Add(Excel.XlFormatConditionType.xlTextString, Excel.XlFormatConditionOperator.xlEqual, "TRUE");
                    Excel.Interior interior = fc.Interior;
                    interior.Color = ColorTranslator.ToOle(Color.LightGreen);
                    Excel.Font font = fc.Font;
                    font.Color = ColorTranslator.ToOle(Color.ForestGreen);
                    fc = (Excel.FormatCondition)fcs.Add(Excel.XlFormatConditionType.xlTextString, Excel.XlFormatConditionOperator.xlEqual, "FALSE");
                    interior.Color = ColorTranslator.ToOle(Color.LightSalmon);
                    font.Color = ColorTranslator.ToOle(Color.Red);

2 个答案:

答案 0 :(得分:0)

您没有将颜色与给定规则相关联(但使用与条件格式无关的变量)。您还应该更好地依赖xlCellValue。此代码提供您所追求的内容:

Excel.FormatCondition fc = (Excel.FormatCondition)fcs.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "TRUE", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
fc.Interior.Color = ColorTranslator.ToOle(Color.LightGreen);
fc.Font.Color = ColorTranslator.ToOle(Color.ForestGreen);

fc = (Excel.FormatCondition)fcs.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "FALSE", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
fc.Interior.Color = ColorTranslator.ToOle(Color.LightSalmon);
fc.Font.Color = ColorTranslator.ToOle(Color.Red);

答案 1 :(得分:0)

(为发布此答案而道歉,但我没有足够的代表来添加评论) 你有一行:

Excel.FormatCondition fc = (Excel.FormatCondition)fcs.Add(Excel.XlFormatConditionType.xlTextString, Excel.XlFormatConditionOperator.xlEqual, "TRUE");

你的第三个参数“TRUE”通常代表公式。如果您希望这个工作,您需要将其更改为“= TRUE”。同样,你有“FALSE”,应更新为“= FALSE”。

您还希望在上面添加@varocarbas建议。