1

I'm trying to put a macro where I select Yes in a row, the next cells are grayed out. So I have got couple of yes columns, but for the life of me can't figure/fix out the error

Error
Runtime Error 1004
Application-defined or object-defied error

Code

Private Sub Worksheet_Change(ByVal Target As Range)

If ActiveCell.Column = 5 Then

    Set r = Range(ActiveCell.Offset(0, 1), ActiveCell.Offset(0, 7))

    If Target.Value = "Yes" Or Target.Value = "YES" Then
        r.Interior.Color = RGB(192, 192, 192)
    Else
        r.Interior.Color = xlNone
    End If
End If

 If ActiveCell.Column = 7 Then

    Set s = Range(ActiveCell.Offset(0, 1), ActiveCell.Offset(0, 3))

    If Target.Value = "Yes" Or Target.Value = "YES" Then
        s.Interior.Color = RGB(192, 192, 192)
    Else
        s.Interior.Color = xlNone
    End If
 End If
End Sub

1

shA.t
  • 16,580
  • 5
  • 54
  • 111
djEthen
  • 29
  • 1
  • 1
  • 7

3 Answers3

1

ActiveCell is not the cell that changed. Target is. You need to replace all of the references to ActiveCell to Target and adjust the offsets accordingly.

Comintern
  • 21,855
  • 5
  • 33
  • 80
1

Changing ActiveCell to Target is a good start. You should also compensate for more than a single target cell in case a block of values is pasted into a range overlapping columns E and/or G.

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Union(Columns(5), Columns(7))) Is Nothing Then
        On Error GoTo Fìn
        Application.EnableEvents = False
        Dim o As Range, t As Range
        For Each t In Intersect(Target, Union(Columns(5), Columns(7)))
            Select Case t.Column
                Case 5
                    Set o = t.Offset(0, 1).Resize(1, 7)
                Case 7
                    Set o = t.Offset(0, 1).Resize(1, 3)
            End Select
            If LCase(t.Value) = "yes" Then
                o.Interior.Color = RGB(192, 192, 192)
            Else
                o.Interior.Pattern = xlNone
            End If
        Next t
    End If

Fìn:
    Set o = Nothing
    Application.EnableEvents = True

End Sub

I've only set the range of the cells to receive the fill color first. Note that there does seem to be a crossover logic issue where if E5 receives a Yes and G5 receives a No then only K5:L5 will be grey. I made the comparison to yes non-case-sensitive.

Errors are covered by a safe exit.

0

Found the issue though, it was using conditional highlighting so that's what was conflicting with the macro

djEthen
  • 29
  • 1
  • 1
  • 7