Excel 通过比较两个不同的关键字填写颜色

Excel 通过比较两个不同的关键字填写颜色,excel,vba,Excel,Vba,我想通过比较具有不同单元格文本的两列来填充整行的颜色。如下图所示,如果我在第1列“支付”和第2列“完成”输入。我想把整行填成绿色 我的代码是: Dim itm As Range Dim rw As Long With Sheets("PO 2019_Vendor") rw = .Range("A" & .Rows.Count).End(xlUp).Row If .Range("AG" & rw).Value = "PAID" And .Range("AJ" & rw)

我想通过比较具有不同单元格文本的两列来填充整行的颜色。如下图所示,如果我在第1列“支付”和第2列“完成”输入。我想把整行填成绿色

我的代码是:

Dim itm As Range
Dim rw As Long
With Sheets("PO 2019_Vendor")
rw = .Range("A" & .Rows.Count).End(xlUp).Row

If .Range("AG" & rw).Value = "PAID" And .Range("AJ" & rw).Value = "DONE" Then itm.EntireRow.Interior.Color = 4

If .Range("AG" & rw).Value = "PAID" And .Range("AJ" & rw).Value = "NOTRCV" Then itm.EntireRow.Interior.Color = 6

If .Range("AG" & rw).Value = "PENDING" And .Range("AJ" & rw).Value = "DONE" Then itm.EntireRow.Interior.Color = 28

End With
End Sub

我希望你能理解我的解释,帮助我解决问题。提前谢谢。

如果该列为
AG
AJ
,且标题位于第一行:

Sub erf()
Dim itm As Range
Dim rw As Long

    With Sheets("PO 2019_Vendor")

        rw = .Range("AG" & .Rows.Count).End(xlUp).Row

        For i = 2 To rw 'only if your headers are in 1 row

        If .Range("AG" & i).Value = "PAID" And .Range("AJ" & i).Value = "DONE" Then Rows(i).Interior.Color = 4

        If .Range("AG" & i).Value = "PAID" And .Range("AJ" & i).Value = "NOTRCV" Then Rows(i).EntireRow.Interior.Color = 6

        If .Range("AG" & i).Value = "PENDING" And .Range("AJ" & i).Value = "DONE" Then Rows(i).EntireRow.Interior.Color = 28

        Next

    End With

End Sub

我有两点建议:

  • 循环通过
    数组
    :由于我不知道要循环通过的行的数量,数组应该要快得多
  • 使用颜色索引时不要使用
    Color
    属性。您可以使用
    颜色
    颜色索引
    。前者采用表示RGB颜色(或RGB(…,…,…,…)语法本身的
    Long
    值。后者采用当前所选颜色主题中的颜色索引。将
    color
    属性与索引号混合使用会将行涂成黑色。我假设您正试图这样做


您需要设置
itm
看起来条件公式就是您的解决方案。
=和($AG1=“PAID”、$AJ1=“DONE”)
等填充设置为正确的颜色。恐怕这回答了一半的问题。
color
属性需要一个表示RGB的
长值。此外(更离题),如果必须循环一个范围,我更喜欢对每个
使用
,因为它比我的
循环快得多(在更大的数据集上)。+1任一选择=)。是的,我的错,它应该是
颜色索引
,用于代码中的数字。哇,感谢您提供有关每个
信息,真的很感谢,也感谢第+1点:)观看关于速度差异的视频(从6:50开始)。也许在一个范围对象中循环不太引人注意(所以我之前的说法是,在一个范围对象上循环速度明显更快是错误的,但它仍然更快。)这就是为什么我如此喜欢它和它的社区,这是非常有用的一课,再次感谢@JvdV,真的,真的非常感谢。
Sub ColorRows()

Dim arr As Variant
Dim rw As Long, x As Long

With Sheet1 'Change according to your sheet's CodeName (see Project Explorer)
    rw = .Cells(.Rows.Count, "AG").End(xlUp).Row
    arr = .Range("AG1:AJ" & rw)
    For x = LBound(arr) To UBound(arr)
        If arr(x, 1) = "PAID" And arr(x, 4) = "DONE" Then .Rows(x).Interior.ColorIndex = 4
        If arr(x, 1) = "PAID" And arr(x, 4) = "NOTRCV" Then .Rows(x).Interior.ColorIndex = 6
        If arr(x, 1) = "PENDING" And arr(x, 4) = "DONE" Then .Rows(x).Interior.ColorIndex = 28
    Next x
End With

End Sub