Search code examples
excelvbarowlistobject

How to highlight target row and column in one or more tables?


The following code works to highlight row 1 in ListObject(2)

Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Cells.Count < 1 Then Exit Sub 
    
    Application.ScreenUpdating = False
    
    'Clear the color of all cells
    Cells.Interior.ColorIndex = 0
    
    Set oList = ActiveSheet.ListObjects(2)
    With Target
        'Highlight row and column of the selected cell
        .EntireColumn.Interior.ColorIndex = 24
        oList.ListRows(1).Range.Interior.ColorIndex = 38
    End With

End Sub

Question: How can I highlight the target row instead?


Solution

  • Use Intersect:

    Dim rng As Range
    Set rng = Intersect(Target.EntireRow, oList.DataBodyRange)
    
    If Not rng Is Nothing Then
        rng.Interior.ColorIndex = 38
    End If
    

    EDIT:

    I would suggest that you add an initial condition to check if Target is inside the table. If not, exit.

    Sub Worksheet_SelectionChange(ByVal Target As Range)
    
        Dim oList As ListObject
        Set oList = Me.ListObjects(2)
    
        ' Only proceed if `Target` is inside the table body
        If Intersect(Target, oList.DataBodyRange) Is Nothing Then Exit Sub
    
        Application.ScreenUpdating = False
        
        'Clear the color of all cells
        Me.Cells.Interior.ColorIndex = 0
        
        Dim rng As Range
        Set rng = Intersect(Target.EntireColumn, oList.DataBodyRange)
        rng.Interior.ColorIndex = 24
    
        Set rng = Intersect(Target.EntireRow, oList.DataBodyRange)
        rng.Interior.ColorIndex = 38
    
        Application.ScreenUpdating = True
    End Sub
    

    EDIT 2:

    If you want to highlight another table's column:

    Dim oList2 As ListObject
    Set oList2 = Me.ListObjects(1)
    
    Set rng = Intersect(Target.EntireColumn, oList2.DataBodyRange)
    If Not rng Is Nothing Then
        rng.Interior.ColorIndex = 24
    End If