基于单元格文本的 Microsoft.Office.Interop.Excel.Cells 上的 C# 条件格式

C# Conditional Formatting on Microsoft.Office.Interop.Excel.Cells based on cell text

我用 C# 和 Microsoft.Office.Interop.Excel 编写代码。在生成的下拉列表中,可以在 "okay"、"delete"、"else" 之间进行选择。现在,如果选择 "delete",我希望单元格变为红色。我试着用 Excel.FormatCondition:

来做到这一点
Excel.FormatCondition condition = mysheet.get_Range("J2:J10",
    Type.Missing).FormatConditions.Add(Type:Excel.XlFormatConditionType.xlTextString,
    Operator: Excel.XlFormatConditionOperator.xlEqual, Formula1: "=\"delete\"");
condition.Interior.ColorIndex = 3;

使用这段代码我得到一个错误:

System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800A03EC'

老问题,但希望这可能对其他人有所帮助。 当您将类型设置为 Type:Excel.XlFormatConditionType.xlTextString 时,您需要设置 String:TextOperator: 参数,而不是问题中所示的 Operator:Formula1:

修复代码:

FormatConditions.Add(Type:Excel.XlFormatConditionType.xlTextString,
    TextOperator: Excel.XlContainsOperator.xlContains, String: "delete");