Search code examples
excelcellhighlight

EXCEL: Click One Cell and Highlight Another


Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    With Sheets("test")
     .Cells.Interior.ColorIndex = xlColorIndexNone
       Select Case Target.Address
        Case "$D$3" 
         .Range("D3").Interior.Color = RGB(195, 195, 195)
         .Range("J3").Interior.Color = RGB(195, 195, 195)
         .Range("V3").Interior.Color = RGB(195, 195, 195)
         Case "$J$3" 
         .Range("D3").Interior.Color = RGB(195, 195, 195)
         .Range("J3").Interior.Color = RGB(195, 195, 195)
         .Range("V3").Interior.Color = RGB(195, 195, 195)
         Case "$V$3" 
         .Range("D3").Interior.Color = RGB(195, 195, 195)
         .Range("J3").Interior.Color = RGB(195, 195, 195)
         .Range("V3").Interior.Color = RGB(195, 195, 195)


        End Select
    End With
End Sub

ASK This code is very large and noob.

Can edit this code " Case "$D$3" " like Case "$D$3:"$J$3:"$V$3" - its not work

And this: .Range("D3").Interior.Color = RGB(195, 195, 195)

Like D3:J3:P3 - not work good


Solution

  • Here is the code with a little syntax change for you:

    Use Intersect function to check and IIF for Toogle

        Option Explicit
        Private Sub Worksheet_SelectionChange(ByVal Target As Range)
            Dim isIntersect As Range
            Dim Listrange As Variant
            Listrange = Array("D3, J3, V3","D5, J4, V8")
            'Listrange = Array("D3, J3, V3","D5, J4, V8","....") ex:add another range
            Dim i As Integer
            For i = 0 To UBound(Listrange)
            With Range(Listrange(i))
                Set isIntersect = Intersect(Target, .Cells)
                .Interior.Color = IIf(isIntersect Is Nothing, xlNone, RGB(195, 195, 195))
            End With
    
            Next i
        End Sub
    

    Note: you can use RGB(255, 195, 255) or 16777215 to replace xlNone