![](/img/trans.png)
[英]C# and Microsoft.Office.Interop.Excel Find all cells merged with given cell
[英]C# Conditional Formatting on Microsoft.Office.Interop.Excel.Cells based on cell text
我用 C# 和Microsoft.Office.Interop.Excel
編寫了一個代碼。 在生成的下拉列表中,您可以在“好的”、“刪除”、“其他”之間進行選擇。 現在我希望如果選擇“刪除”,則該單元格變為紅色。 我試圖用Excel.FormatCondition
做到這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'
老問題,但希望這可能對其他人有所幫助。 當您將類型設置為Type:Excel.XlFormatConditionType.xlTextString
,您需要設置String:
和TextOperator:
參數而不是Operator:
和Formula1:
如問題所示。
修復代碼:
FormatConditions.Add(Type:Excel.XlFormatConditionType.xlTextString,
TextOperator: Excel.XlContainsOperator.xlContains, String: "delete");
我找到了解決方案。 很簡單。 我不得不使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.