C# 动态更改FormatCondition的范围

C# 动态更改FormatCondition的范围,c#,excel,vsto,conditional-formatting,C#,Excel,Vsto,Conditional Formatting,我使用下面的代码在一个范围中添加了一个格式条件,其中包含一些格式 Microsoft.Office.Interop.Excel.FormatCondition formatConditionObj = null; formatConditionObj = (Microsoft.Office.Interop.Excel.FormatCondition)myRange .FormatConditions.Add(Excel.XlFormatConditionType.xlExpressio

我使用下面的代码在一个范围中添加了一个格式条件,其中包含一些格式

Microsoft.Office.Interop.Excel.FormatCondition formatConditionObj = null;

formatConditionObj = (Microsoft.Office.Interop.Excel.FormatCondition)myRange
    .FormatConditions.Add(Excel.XlFormatConditionType.xlExpression, 
    Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing);

formatConditionObj.Interior.ColorIndex = 5;
现在,我的范围动态地改变了。
。我希望使用相同的FormatCondition对象,我只改变应用这些格式的范围。例如,首先可能是
“$A$1”
,之后可能是
“$A$2,$D$5”
“$A$3:$A$20”


这可以直接使用excel完成。继续格式->管理规则->应用于(编辑此)。使用C#如何实现这一点。

这对我很有用。我发现把下面的“使用”行放在顶部可以节省很多精力

using Microsoft.Office.Interop.Excel;

<...>

        formatConditionObj = (FormatCondition)myRange.FormatConditions
            .Add(XlFormatConditionType.xlExpression, 
            Type.Missing, true, Type.Missing, Type.Missing, 
            Type.Missing, Type.Missing, Type.Missing);

        formatConditionObj.Interior.ColorIndex = 5;

        Range myNewRange = ws.Range["a10:a15"];
        formatConditionObj.ModifyAppliesToRange(myNewRange);

 <...>
使用Microsoft.Office.Interop.Excel;
formatConditionObj=(FormatCondition)myRange.FormatConditions
.Add(XlFormatConditionType.xlExpression,
Type.Missing,true,Type.Missing,Type.Missing,
类型。缺失,类型。缺失,类型。缺失);
formatConditionObj.Interior.ColorIndex=5;
Range myNewRange=ws.Range[“a10:a15”];
formatConditionObj.ModifyAppliesToRange(myNewRange);

在formatConditionObj上应用myNewRange后,尝试访问formatConditionObj的公式(公式1)时,使用ModifyAppliesToRange会出现异常。为什么会有这种行为?你可能想问一个新的问题,并提供一些额外的细节,因为我不太清楚你的意思。我提出了一个新的问题,请参考此链接