2012-08-02 133 views
0

我已经使用下面的代码在某个范围上添加了格式条件。动态更改FormatCondition的范围

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; 

现在我的变化范围dynamically。我想使用相同FormatCondition对象我只是改变其中该格式应用的范围。例如,首先它可能只是"$A$1",它可能是"$A$2,$D$5""$A$3:$A$20"

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

回答

0

这适用于我。我发现把顶端的“使用”一行放在顶端可以节省很多努力。

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); 

<...> 
+0

由于Remou其工作:) – 2012-08-02 10:55:32

+0

使用ModifyAppliesToRange给人试穿formatConditionObj应用myNewRange后访问formatConditionObj的公式(一级方程式)时异常。这是为什么? – 2012-08-21 04:24:48

+0

你可能会问,作为一个新的问题与一些额外的细节,因为我非常确定你的意思。 – Fionnuala 2012-08-21 10:29:14