2016-12-07 334 views
0

如何編碼多個條件格式?目前,我只能編碼一個條件格式。如何在VBA編碼中添加多個條件格式 - EXCEL

我的代碼:

Sub Button5_Click() 
Dim ws As Worksheet 
Dim i As Integer 
Set ws = Sheets("COMPARISON") 
i = 1 

With Range("I2:I146").FormatConditions.Add(_ 
    Type:=xlExpression, _ 
    Formula1:="=((($I2-$E2)/$E2)*100) > 20") 
    .Interior.Color = RGB(255, 0, 0) 

End With 

Do Until i = 300 
    If ws.Range("I" & i).DisplayFormat.Interior.Color = RGB(255, 0, 0) Then 
     msg = "I" & i & " -" & " Data has changed" 
     MsgBox msg 
    End If 
i = i + 1 
Loop 

End Sub 

我已經設法創造一個條件格式,其中如果I2的值 - E2是20%以上,填充單元格的紅色。

我想創建兩個條件格式編排這樣其中

1)如果所述細胞是0填充細胞黑和設置字體白色

2)如果小區I2是< E2但不爲0填滿細胞黃色。

有人可以幫助我與其他2條件格式?非常感謝。

+2

難道你只是記錄條件? – nightcrawler23

+0

我的「老闆」不想記錄條件的想法.... – Joel

+0

另外,如果我記錄的條件格式有太多的代碼在vba中,我不知道哪些代碼將是必要的,因爲我'在excel vba中,贊成/好。因此,從頭開始編寫vba代碼,我有點了解代碼 – Joel

回答

0

我剛剛複製了With塊並應用了您擁有的條件。你可以試試這個:

Sub Button5_Click() 
Dim ws As Worksheet 
Dim i As Integer 
Set ws = Sheets("COMPARISON") 
i = 1 

With Range("I2:I146").FormatConditions.Add(_ 
    Type:=xlExpression, _ 
    Formula1:="=((($I2-$E2)/$E2)*100) > 20") 
    .Interior.Color = RGB(255, 0, 0) 

End With 

With Range("I2:I146").FormatConditions.Add(_ 
    Type:=xlCellValue, _ 
    Operator:=xlEqual, _ 
    Formula1:="0") 
    .Interior.Color = RGB(0, 0, 0) 
    .Font.Color = RGB(255, 255, 255) 
End With 

With Range("I2:I146").FormatConditions.Add(_ 
    Type:=xlExpression, _ 
    Formula1:="=AND($I2<$E2, $I2<>0)") 
    .Interior.Color = RGB(255, 255, 0) 
End With 

Do Until i = 300 
    If ws.Range("I" & i).DisplayFormat.Interior.Color = RGB(255, 0, 0) Then 
     msg = "I" & i & " -" & " Data has changed" 
     MsgBox msg 
    End If 
i = i + 1 
Loop 

End Sub 
+0

@Joel將我的答案標記爲正確答案會很好。 :) –

+0

當然:)再次感謝您的幫助。 – Joel