Search code examples
excelvbanamed-ranges

How to compare values of corresponding cells in multiple named column ranges and change interior color in another corresponding cell


I want to write a code in Excel VBA that compares the values in corresponding cells in 3 named ranges (say, "Peter", "Paul" & "John"), and if all three values are >= 3, then the interior color of the corresponding cell in a fourth named range say, "James", is changed to Green. I wrote the code using offset but the code doesn't work properly if I insert new columns in-between "Peter", "Paul" and "John". Please can you help me write a code that uses named ranges, to avoid an error when new columns are added? Thank you.

If Cell.Value >= 3 Then
            If Cell.Offset(0, 1).Value >= 3 Then
                If Cell.Offset(0, 2).Value >= 3 Then
                    If Cell.Offset(0, 3).Value >= 3 Then
                        Cell.Offset(0, 4).Interior.ColorIndex = 4
                    End If
                End If
            End If
        End If
    Next Cell

Solution

  • This works

    Dim xCel As Range, rPtr As Long
    Dim xSht As Worksheet
    
    Set xSht = ActiveSheet
    rPtr = 0
    For Each xCel In xSht.Range("Peter").Cells
       rPtr = rPtr + 1
       If xCel.Value >= 3 Then
          If xSht.Range("Paul").Cells(rPtr, 1).Value >= 3 Then
             If xSht.Range("John").Cells(rPtr, 1).Value >= 3 Then
                xSht.Range("James").Cells(rPtr, 1).Interior.ColorIndex = 34
             End If
          End If
       End If
    Next xCel
    

    This solves the problem you mentioned, but it still presumes all ranges are the same length and single column