2014-01-23 78 views
1

我試圖在各種選定範圍上運行一系列宏來檢查並查看單元格的數值是否大於指定值。這裏的例子是對於值大於0.7的單元格,除了它們使用大於值的不同之外,其他宏類似。將Excel條件格式公式調整爲選定範圍

我的問題似乎在於用於確定條件格式的公式;如果公式調用我選擇的列內的單元格,則該宏將起作用,否則它不會執行任何操作。

舉個例子:我選擇單元格D5:D15,然後運行下面的宏:

Sub Toluene() 
' 
' Toluene Macro 
' Apply conditional formatting to Toluene cells with values greater than 0.7 
' 

' 
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ 
    "=AND(ISNUMBER(D5),D5>0.7)" 
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority 
With Selection.FormatConditions(1).Font 
    .Bold = True 
    .Italic = True 
    .TintAndShade = 0 
End With 
With Selection.FormatConditions(1).Interior 
    .PatternColorIndex = xlAutomatic 
    .ThemeColor = xlThemeColorAccent6 
    .TintAndShade = 0.799981688894314 
End With 
Selection.FormatConditions(1).StopIfTrue = False 
End Sub 

工作正常。但是,如果我選擇單元格G5:G10,並嘗試將相同的宏應用於它,則不會發生任何事情(不會應用正確的條件格式)。

我在想正確的,我需要以某種方式改變我的公式

"=AND(ISNUMBER(D5),D5>0.7)" 

,以反映所選列,如果是這樣,沒有人對我怎麼可能做到這一點建議嗎?

回答

0

嘗試使用R1C1引用樣式:

Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ 
"=AND(ISNUMBER(RC),RC>0.7)" 

,或者如果你不喜歡這個,你可以使用更復雜的代碼:

Dim topLeftAddr As String 

topLeftAddr = Replace(Selection.Cells(1, 1).Address, "$", "") 

Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ 
"=AND(ISNUMBER(" & topLeftAddr & ")," & topLeftAddr & ">0.7)" 
+1

真棒 - 感謝這麼多simoco - 使用R1C1引用工作! –