首页 > 解决方案 > Excel 范围上的条件格式为每个单元格都具有向上箭头图标,而不管包含的值如何

问题描述

我的目标是突出显示 Excel 范围的一部分(我可以使用条件格式来完成),但现在它还需要在上述范围内的每个单元格中添加向上箭头。

如何做到这一点?


我尝试过的是这样的

var wb = Globals.ThisAddIn.Application.ActiveWorkbook;
var formatIcon = rngExistingColumns.FormatConditions.AddIconSetCondition() as Excel.IconSetCondition;
formatIcon.Formula = "=1";
formatIcon.IconSet = wb.IconSets[Excel.XlIconSet.xl3Arrows];

var crit1 = formatIcon.IconCriteria;

crit1[1].Type = Excel.XlConditionValueTypes.xlConditionValueFormula;
crit1[1].Operator = (int) Excel.XlFormatConditionOperator.xlGreater;
crit1[1].Value = 0;

但我没有得到任何结果,只会抛出 com 异常。

标签: c#excelvstoconditional-formatting

解决方案


不要手动设置红色图标的规则,crit1[1]因为红色图标是反对绿色/黄色图标规则的最后一条规则。

我的示例代码有效,它只是设置了绿色/黄色规则。值 60 为黄色,值 80 和 90 为绿色,另一个为红色。

var wb = Globals.ThisAddIn.Application.ActiveWorkbook;

wb.ActiveSheet.Range["A1"].Value2 = "20";
wb.ActiveSheet.Range["A2"].Value2 = "80";
wb.ActiveSheet.Range["A3"].Value2 = "60";
wb.ActiveSheet.Range["A4"].Value2 = "40";
wb.ActiveSheet.Range["A5"].Value2 = "30";
wb.ActiveSheet.Range["A6"].Value2 = "90";

// Add an icon set condition to the range
Excel.IconSetCondition iconSetCondition1 =
    (Excel.IconSetCondition)
    wb.ActiveSheet.Range["A1", "A6"].
    FormatConditions.AddIconSetCondition();

iconSetCondition1.SetFirstPriority();
iconSetCondition1.ShowIconOnly = false;

iconSetCondition1.IconSet =
    Excel.XlIconSet.xl3Arrows;

var yellowIcon = iconSetCondition1.IconCriteria[2];
yellowIcon.Type = Excel.XlConditionValueTypes.xlConditionValueNumber;
yellowIcon.Operator = (int)Excel.XlFormatConditionOperator.xlGreaterEqual;
yellowIcon.Value = Convert.ToDouble(60);

var greenIcon = iconSetCondition1.IconCriteria[3];
greenIcon.Type = Excel.XlConditionValueTypes.xlConditionValueNumber;
greenIcon.Operator = (int)Excel.XlFormatConditionOperator.xlGreaterEqual;
greenIcon.Value = Convert.ToDouble(80);

2020/08/25更新 如果您希望最上面的规则是红色的,第二个规则是绿色的,最后一个是黄色的,您可以设置Icon更改规则顺序。

在我的示例中,值 60 将是绿色,值 80 和 90 将是红色,另一个将是黄色。

var greenIcon = iconSetCondition1.IconCriteria[2];
greenIcon.Icon = Excel.XlIcon.xlIconGreenCircle;
greenIcon.Type = Excel.XlConditionValueTypes.xlConditionValueNumber;
greenIcon.Operator = (int)Excel.XlFormatConditionOperator.xlGreaterEqual;
greenIcon.Value = Convert.ToDouble(60);

var redIcon = iconSetCondition1.IconCriteria[3];
redIcon.Icon = Excel.XlIcon.xlIconRedCircle;
redIcon.Type = Excel.XlConditionValueTypes.xlConditionValueNumber;
redIcon.Operator = (int)Excel.XlFormatConditionOperator.xlGreaterEqual;
redIcon.Value = Convert.ToDouble(80);

var yellowIcon = iconSetCondition1.IconCriteria[1];
yellowIcon.Icon = Excel.XlIcon.xlIconYellowCircle;

推荐阅读