我用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'
答案 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