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

时间:2019-06-20 16:13:02

标签: c# excel-formula excel-interop

我用C#和Microsoft.Office.Interop.Excel编写代码。在生成的下拉列表中,可以在“确定”,“删除”,“其他”之间进行选择。现在,我希望如果选择“删除”,该单元格将变为红色。我试图用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:'来自HRESULT的异常:   0x800A03EC'

2 个答案:

答案 0 :(得分:1)

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

修复代码:

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

答案 1 :(得分:0)

我找到了解决方案。很简单。我必须使用XlFormatConditionType.xlCellValue而不是TextString:

//Drop-down List
var list = new System.Collections.Generic.List<string>();

list.Add("okay");
list.Add("delete");
list.Add("else (Comment)");
var flatList = string.Join(",", list.ToArray());

var celldd = (Excel.Range)mysheet.Cells[row_counter, 10];

celldd.Validation.Delete();
try
{
    int type = celldd.Validation.Type;
    Console.WriteLine("The validation have already been added");
}
catch (System.Runtime.InteropServices.COMException)
{
    celldd.Validation.Add(
    Excel.XlDVType.xlValidateList,
    Excel.XlDVAlertStyle.xlValidAlertInformation,
    Excel.XlFormatConditionOperator.xlBetween,
    flatList, misValue);
 }
 celldd.Validation.InCellDropdown = true;
 celldd.Validation.IgnoreBlank = true;
 celldd.Locked = false;

 celldd.Value2 = "Choose";
 celldd.Interior.Color = ColorTranslator.ToOle(Color.Plum);

 //Conditional Formatting
 Excel.FormatCondition condition1 = mysheet.get_Range("J2:J10",
        Type.Missing).FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "=\"delete\"", misValue, misValue, misValue, misValue, misValue);
 condition1.Interior.ColorIndex = 3;  //red

 Excel.FormatCondition condition2 = mysheet.get_Range("J2:J10",
        Type.Missing).FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "=\"okay\"", misValue, misValue, misValue, misValue, misValue);
 condition2.Interior.ColorIndex = 43; //green

Excel.FormatCondition condition3 = mysheet.get_Range("J2:J10",
        Type.Missing).FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "=\"else (Comment)\"", misValue, misValue, misValue, misValue, misValue);
condition3.Interior.ColorIndex = 44;  //yellow