如何在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填充细胞黄色。

有人可以帮助我使用其他两种条件格式吗?非常感谢。

我只是复制了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

最新更新