Excel Tip- Highlight the Row

Using the following code we can able to highlight the row where the cursor is available without affecting the data
Copy the code -Right click Tab Name > View code and paste the code there on the VBE window.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    
    '// Developed by Kris @ ExcelFox.com
    
    Dim x, nmRow    As Name
    
    'if A1 holds '0', the macro won't fire
    If Me.Range("A1") = 0 Then Exit Sub 'adjust the flag cell
        
    On Error Resume Next
    Set nmRow = ThisWorkbook.Names("tRow")
    On Error GoTo 0
    
    Const HighlightColor As Long = 6750207 'Adjust the highlight color

    If nmRow Is Nothing Then
        Set nmRow = ThisWorkbook.Names.Add("tRow", Target.Row & "|" & Target.EntireRow.Interior.Color, 0)
        Target.EntireRow.Interior.Color = HighlightColor
    Else
        x = Split(Evaluate("tRow"), "|")
        Me.Rows(CLng(x(0))).Interior.Color = IIf(CLng(x(1)) = 16777215, -4142, CLng(x(1)))
        nmRow.RefersTo = Target.Row & "|" & Target.EntireRow.Interior.Color
        Target.EntireRow.Interior.Color = HighlightColor
    End If

End Sub
Or you can highlight both row and column

Public PreviousTarget As Range


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Not PreviousTarget Is Nothing Then PreviousTarget.Interior.ColorIndex = xlColorIndexNone
  Set PreviousTarget = Union(Target.EntireRow, Target.EntireColumn)
  PreviousTarget.Interior.ColorIndex = 6
End Sub

No comments:

Post a Comment