2014-10-31 183 views
0

我被卡住了,我不知道是否有任何解決方案,因爲我已經嘗試過很多並且一直在失敗。Excel VBA公式中的條件格式公式

Sample

我試圖使細胞在B列變爲黃色添加條件格式,如果它等於或它的不到19%,在A列伴侶細胞,所以在上面的例子中,B1單元格應因爲19,000美元不到或等於100,000美元的19%。

我需要通過excel vba添加這個條件格式。我嘗試添加下面的vba代碼,但B1:B3中的所有單元格的條件格式公式都與$A1*0.19卡住了。我需要B1條件格式化公式爲$A1*0.19,那麼B2條件格式化公式將是$A2*0.19等等。我有大約350行的方式不只是3.即使如此,我的vba代碼成爲$A521325*0.19或某種方式的真實或實際。

With Sheet1.Range(Sheet1.Cells(1, 2), Sheet1.Cells(3, 2)) 
    daformula = "=$A1*0.19" 
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, Formula1:=daformula 
    .FormatConditions(.FormatConditions.Count).SetFirstPriority 
     .FormatConditions(1).Interior.PatternColorIndex = xlAutomatic 
     .FormatConditions(1).Interior.ThemeColor = xlThemeColorAccent2 
     .FormatConditions(1).Interior.TintAndShade = -0.249946592608417 
    .FormatConditions(1).StopIfTrue = False 
End With 

的想法是運行的添加條件格式到片材中,當用戶改變單元中的一個在列B中的顏色或者消失或根據值再現用戶變更的小區到宏後(條件格式必須仍然有效)

+0

我測試了你的上面的代碼,它工作的很好。正常工作[這裏](https://www.dropbox.com/s/er3imeavayvrkmo/Test.xlsm?dl=0) – 2014-11-03 15:43:36

+0

不,我恐怕沒有。在鏈接中使用該文件,嘗試刪除所有條件格式,然後再次運行代碼。你會看到38箇中的200個不會變紅,其他的也不變。它搞砸了。這看起來確實很難:s – Jay 2014-11-03 20:51:36

+0

不知道該告訴你什麼,代碼對於Excel 2010是正確的。我想如果你有不同的版本,我沒有太大的幫助:( – 2014-11-03 20:57:12

回答

1

嘗試,

With ActiveSheet.Cells(1, 2).Resize(3, 1) 
    .FormatConditions.Add Type:=xlExpression, Formula1:="=$B1<=($A1*0.19)" 
    .FormatConditions(.FormatConditions.Count).Interior.Color = 65535 
End With 

無論你添加像.SetFirstPriority.StopIfTrue其他細節將在另一塊CF規則如何影響同一細胞某種程度上取決於。

1

你可以創建一個監視A列中的任何改變(發生這種代碼在工作表Sheet1對象)

Private Sub Worksheet_Change(ByVal Target As Range) 

    If Target.Column = 1 Then 

     'run code to add conditional formatting 
     condFormat Target 

    End If 

End Sub 

現在,我們只需要改變你的上面的代碼以接受目標和只添加格式化事件在B列的等效電池

Public sub condFormat (Target as range) 
    With target.offset(0,1) 
     daformula = "=" & target.address & "*0.19" 
     .FormatConditions.Add Type:=xlCellValue, Operator:=xlLessEqual, _ 
           Formula1:=daformula 
     .FormatConditions(.FormatConditions.Count).SetFirstPriority 
     .FormatConditions(1).Interior.PatternColorIndex = xlAutomatic 
     .FormatConditions(1).Interior.ThemeColor = xlThemeColorAccent2 
     .FormatConditions(1).Interior.TintAndShade = -0.249946592608417 
     .FormatConditions(1).StopIfTrue = False 
    End With 
end sub 

我沒有佔一次改變超過1個細胞,但是這將解決你的挑戰

+0

我忘了說,整個數據庫正在Excel VBA中處理,然後上傳到Google Docs。這就是爲什麼我們需要CF,因爲在上傳到Google文檔時也包含CF – Jay 2014-10-31 18:31:44

0

當肌酐從VBA條件格式化,相對於條件格式公式的單元格選擇至關重要。

嘗試使用ActiveSheet.cells(1,1).select如果條件格式公式只訪問同一行上的值,或者ActiveSheet.cells(2,1)如果它引用上述行的值。