浏览列并突出显示行。

时间:2017-07-26 13:26:21

标签: excel vba excel-vba

我有一张“数据”表,我从G到P的列填充了Price。我在同一张表中有另一列U具有最高价格。 (目标价格)。

我现在想检查每一行,如果G到P之间的任何一列的价格高于我的列U中的目标价格,那么我想用红色突出显示完整的行。

我尝试了类似下面的代码,但它有用。任何人都可以建议,我如何查看每个列并与目标进行比较并突出显示。如果你可以评论你的代码行,那将是很棒的。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer

For i = 7 To 16
    If Cells(Target.Row, 21).Value <= Cells(Target.Row, i).Value Then
        Target.EntireRow.Interior.Color = vbRed
    End If
Next i

For i = 7 To 16
    If Cells(Target.Row, 21).Value > Cells(Target.Row, i).Value Then
        Target.EntireRow.Interior.ColorIndex = xlNone
    End If
Next i

    If Cells(Target.Row, 22).Value = "x" Then
        Target.EntireRow.Interior.ColorIndex = xlNone
    End If

End Sub

2 个答案:

答案 0 :(得分:0)

我仍然会在条件格式的帮助下执行此操作,但是您坚持使用VBA应用。

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
Dim lr As Long
Dim rng As Range
If Target.Row >= 7 And Not Intersect(Target, Range("G:P")) Is Nothing Then
    lr = Cells(Rows.Count, "U").End(xlUp).Row
    Set rng = Range("G7:U" & lr)
    With rng
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
            "=AND(ROW($G7)>=7,G7<>"""",$U7<>"""",MAX($G7:$P7)>=$U7)"
        .FormatConditions(rng.FormatConditions.Count).SetFirstPriority
        .FormatConditions(1).Interior.Color = 65535
        .FormatConditions(1).StopIfTrue = False
    End With
End If
End Sub

答案 1 :(得分:0)

试试这个

Private Sub Worksheet_Change(ByVal Target As Range)
    If Cells(Target.Row, 22).Value = "x" Or Application.Max(Target.Rows) < Cells(Target.Row, 21) Then
        Cells(Target.Row, 1).EntireRow.Interior.Color = xlNone
    Else
        Cells(Target.Row, 1).EntireRow.Interior.Color = vbRed
    End If
End Sub