2013-03-05 132 views
2

我想以編程方式使用Excel 2007的條件格式功能。我有以下情況。以編程方式在Excel 2007中以編程方式添加條件格式

我有一個數字

A B C D E F 
100 25 25 15 20 50 
.... 

if (C1/A1)*100 >= B1我要顏色爲紅色的6列。同樣的規則適用於D1,E1,F1列。

我在Excel 2007中看到了條件格式化功能。但我想了解如何在C#代碼中實現它的一些指針。

+0

我很確定Google知道該怎麼辦) – Ksenia 2013-03-05 16:31:18

回答

8

我打算假設您很高興使用Interop,因爲您沒有另行說明。這是我用來在Excel中設置條件格式的東西。它假定您已經在名爲xlWorksheet的變量中引用了Worksheet

// Create a FormatCondition and add it to the specified range of cells, using the 
// passed-in condition and cell colour 

Excel.Range range = xlWorksheet.get_Range("C1", "C1"); 
Excel.FormatConditions fcs = range.FormatConditions; 
Excel.FormatCondition fc = (Excel.FormatCondition)fcs.Add 
    (Excel.XlFormatConditionType.xlExpression, Type.Missing, "=IF($C$1/$A$1)*100 >= $B$1"); 
Excel.Interior interior = fc.Interior; 
interior.Color = ColorTranslator.ToOle(Color.Red); 
interior = null; 
fc = null; 
fcs = null; 
range = null; 

我已經猜測了一下您的預期用法,但您可以用它來調整它以獲得公式和單元格引用。

+0

thnx爲答案。但是,當我使用代碼Im得到以下錯誤消息=「方法未找到:」Microsoft.Office.Interop.Excel.FormatCondition Microsoft.Office.Interop.Excel.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType,System .Object,System.Object,System.Object)'。「 – Rajneesh 2013-03-06 09:20:13

+0

@Rajneesh對不起,我的代碼中有一個錯字。我沒有正確關閉支架。再給它一次。如果它仍然不起作用,請顯示導致錯誤的語句。 – 2013-03-06 16:06:43

+0

VS Intillesense在使用3個參數的add方法時顯示錯誤。因此,我使用了FormatCondition formatCondition =(Excel.FormatCondition)formatConditions.Add(XlFormatConditionType.xlExpression,Type.Missing,「= D2/B2 * 100> = C2」,Type.Missing);但是,在執行代碼時,它顯示了我在之前的評論中提到的錯誤。 – Rajneesh 2013-03-07 04:48:23