2012-04-20 61 views
6

如果值與另一列中的值不同,我需要將顏色應用於單元格的文本。最好的方法是什麼?我能想到的方式非常昂貴。使用C#在Excel中進行條件格式化#

for (int i = 0; i < ColumnARange.Cells.Count; i++) 
        { 
         if (ColumnARange.Cells[i, 1] != ColumnBRange.Cells[i, 1]) 
         { 
          Range currCell = ColumnBRange.Cells[i, 1]; 
          currCell.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); 
         } 
        } 

嘗試條件格式如下,但徒勞無功。

FormatCondition cond = ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, ColumnARange); 
       cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); 

我使用VSTO,C#

+0

條件格式? – mellamokb 2012-04-20 04:24:19

+0

是的。需要通過與其他列的值進行比較來將顏色應用於單元格文本。但是如果我像我的代碼中提到的那樣遍歷,考慮具有更多行和列的大數據將會非常昂貴。 – Cannon 2012-04-20 04:27:02

回答

7

下面的代碼,增加了一個條件格式D1至E10

單元格區域它的值D1 = E1或D2 = E2分別進行比較。您可以設置FormatCondition對象的字體顏色或顏色填充。

FormatCondition format =(FormatCondition)(targetSheet.get_Range("D1:E10", 
       Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, XlFormatConditionOperator.xlEqual, 
       "=$D1=$E1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)); 

      format.Font.Bold = true; 
      format.Font.Color = 0x000000FF; 
+1

但我該如何處理動態範圍? – Cannon 2012-04-20 13:42:44

+0

@buffer_overflow檢查[鏈接](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.get_range(v = vs.80).aspx)的聲明get_range方法,可以分別使用targetSheet.Cells [1,2]和targetSheet.Cells [3,4]提供單元格1 n 2。我希望你能用它 – Akanksha 2012-04-21 12:49:32

+0

如果只有一列只能重複一次?例如,檢查所有「D1」...如果存在兩個重複項,請突出顯示它。 – Si8 2016-12-16 14:44:48

1

試試這個

FormatCondition cond = ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "=$B1"); 
       cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); 
1

比方說,你要的顏色細胞B1:B10如果它們的值不等於那些A1:A10,即

B1<>A1結果B1而變色,B2<>A2結果B2正在着色等。

然後你c一個執行以下操作

Range columnBRange = (Range)oSheet.Range[oSheet.Cells[1,2], oSheet.Cells[10,2]]; 

Range columnARange = (Range)oSheet.Range[oSheet.Cells[1,1], oSheet.Cells[1,1]]; 

FormatCondition cond = (FormatCondition) ColumnBRange.FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlNotEqual, "="+ColumnARange.Address[false,true]); 
cond.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); //Red letters 
cond.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow); //Light yellow cell background 

注意,前面加上"="ColumnARange.Address[false,true]因爲否則Add方法使用Address作爲文字串,而不是一個單元格引用是必需的。

如果採取看看在Excel工作表應用於B1:B10細胞條件格式編排規則將說明Cell Value <> B1爲這是一個有點混亂IMO但格式正確應用仍然在範圍內的每一個細胞。

爲了完整性:我使用的可選對象上Range.Address財產像這樣Range.Address[isRowAbsolute,isColumnAbsolute]