2013-07-10 140 views
0

請高手幫忙。以下VBA代碼在Excel 2010中可用,但在2007中不可用。 它顯示錯誤「應用程序或對象未定義」。看起來「selection.FormatConditions.Font」不受支持。VBA宏中的條件格式不工作在Excel 2007中

Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ 
    Formula1:="=""BREAK TOP""" 
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority 
With Selection.FormatConditions(1).Font 
    .Color = -16752384 --- Error: application and object undefined 
    .TintAndShade = 0 
End With 

非常感謝!

+1

這[在Excel 2007被支撐](http://msdn.microsoft.com/en-us/library/office/bb223827(V = office.12)的.aspx)根據開發參考。我在2010年測試代碼,它正在工作。無論如何,如果'.Font'是一個問題,錯誤將發生在'With Selection.FormatConditions(1).Font'行,而不是'.Color'語句。 –

+0

@DavidZemens謝謝!如果註釋掉「.Color」和「.TintAndShade」,程序可以無誤地運行。我已經更新了Microsoft的兼容包,但仍然無濟於事。友善的建議! – rpg

+0

我認爲你需要在2007年使用'RGB'顏色分配。這不適用於負值的顏色值。我會發布更詳細的答案。 –

回答

0

我不能在2007年的Excel中測試這個,但是這個錯誤絕對不是FormatConditions.Font的對象。該錯誤在.Font.Color的評價中提高。

回顧2007年.Font對象的開發參考,似乎應該使用RGB()公式來分配顏色。

http://msdn.microsoft.com/en-us/library/office/bb213182(v=office.12).aspx

然而,我的谷歌賦表明您不能使用負的顏色值與RBG分配。我認爲你需要選擇不同的顏色。也許有一些使用WinAPI的方法,但我目前無法測試這種方法。

我選擇了另一個與您的-16752384色調相似的藍色。

Sub test() 

'## This section converts a long color to its R/G/B components 
    Dim col As Long: col = 15773696 
    Dim r As Long, g As Long, b As Long 
    r = col Mod 256 
    g = (col \ 256) Mod 256 
    b = (col \ 256 \ 256) Mod 256 

'## Your code, with modification for the RGB Formula: 
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ 
     Formula1:="=""BREAK TOP""" 
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority 
    With Selection.FormatConditions(1).Font 
     .Color = RGB(r, g, b) '<-- RGB Formula, here. 
     .TintAndShade = 0 
    End With 


End Sub 

UPDATE

試試這個,不要使用Selection對象。

Sub test2() 

Dim rng as Range 
Dim fc as FormatCondition 
Set rng = Range(Selection.Address) 

'## This section converts a long color to its R/G/B components 
    Dim col As Long: col = 15773696 
    Dim r As Long, g As Long, b As Long 
    r = col Mod 256 
    g = (col \ 256) Mod 256 
    b = (col \ 256 \ 256) Mod 256 

'## Your code, with modification for the RGB Formula: 
    rng.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ 
     Formula1:="=""BREAK TOP""" 
    rng.FormatConditions(rng.FormatConditions.Count).SetFirstPriority 

    Set fc = rng.FormatConditions(1) 
    fc.Font.Color = RGB(r, g, b) '<-- RGB Formula, here. 
    fc.Font.TintAndShade = 0 

End Sub 
+0

謝謝!但是我仍然有同樣的錯誤。我試着通過放入「.Color = 3」來測試它,但仍然出現「錯誤1004:應用程序和對象未定義」。請幫忙! – rpg

+0

如果你把'.Color = 3',那麼你沒有**嘗試我所建議的。再試一次。準確複製我的代碼,然後運行它。讓我知道它是否有效。 –

+0

嗨大衛我試了你的代碼和我的。兩者停在相同的地方,並顯示相同的錯誤。非常感謝!! – rpg