Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight multiple table row only instead of entire row

Tags:

excel

vba

Is there a way to only highlight multiple active cell rows only within the table range instead of the entire sheet row? I have tried conditional formatting but it does not work for multiple active cell selection.

Here is my current working code. Thank you

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Application.ScreenUpdating = False

With Target
  EntireRow.Interior.ColorIndex = 36
End With

Application.ScreenUpdating = True

End Sub

like image 247
Susmaryosep Avatar asked Dec 22 '25 09:12

Susmaryosep


1 Answers

I recommend the following:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim Table As ListObject
    Set Table = Target.ListObject
    
    If Not Table Is Nothing Then
        Dim ColorRange As Range
        Set ColorRange = Application.Intersect(Table.DataBodyRange, Target.EntireRow)
        If Not ColorRange Is Nothing Then
            ColorRange.Interior.ColorIndex = 36
        End If
    End If
End Sub

Target.ListObject will point to the table of the selected cell without having to hard code the tables name. Also if you Intersect with Table.DataBodyRange it does not color the headline of the table but only the data range. Using Intersect it is always recommended to check if the two ranges intersected at all If Not ColorRange Is Nothing Then before using them, otherwise you easily run into errors.

Note that with the code above it will add colored rows to the table. enter image description here

If you want to color only the currently selected row then use the code below:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim Table As ListObject
    Set Table = Target.ListObject
    
    If Not Table Is Nothing Then
        ' decolorize prevously colored rows
        With Table.DataBodyRange.Interior
            .Pattern = xlNone
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
        
        Dim ColorRange As Range
        Set ColorRange = Application.Intersect(Table.DataBodyRange, Target.EntireRow)
        If Not ColorRange Is Nothing Then
            ColorRange.Interior.ColorIndex = 36
        End If
    End If
End Sub

enter image description here

like image 105
Pᴇʜ Avatar answered Dec 23 '25 23:12

Pᴇʜ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!