Search code examples
excelvbaconditional-statementshighlight

Highlighting Cells based on Active row Values


I am stuck on trying to make my sheet highlight the values in Row 2 based on the Active Cell Row values, in this case I am comparing cells "B2:F2" with the Active Row (B3:F3) in this case. Here is how the sheet looks before selecting an active cell/row;

enter image description here

and once I select an active cell (in this case, I selected cell "A3") and would like to compare the "B3:F3" cell values with a static row (B2:F2) and highlight any cells in the static row (B2:F2) that are different than the active row values. The follow screenshot is how the sheet should look once I select cell "A3" as the active cell and have the code/conditional formatting combination compare it with the static row values;

enter image description here

So far, I have this code that highlights the Active cell I am selecting, this is my starting point:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static xLastRng As Range
On Error Resume Next
Target.Interior.ColorIndex = 6
xLastRng.Interior.ColorIndex = xlColorIndexNone
Set xLastRng = Target
End Sub

Please let me know if anything doesn't make sense and your suggestions, thank you!


Solution

  • Perhaps the following - basically compare your fixed range B2:F2 to the corresponding range in the current row:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Me.Range("B2:F2").Interior.Color = xlNone 'clear previous coloring
    
        Dim rng As Range
        For Each rng In Me.Range("B2:F2")
            If IsNumeric(rng.Value) And IsNumeric(Me.Cells(Target.Row, rng.Column)) Then
                If rng.Value <> Me.Cells(Target.Row, rng.Column).Value Then
                    rng.Interior.Color = vbYellow
                End If
            End If
        Next
    End Sub