Microsoft Tech Community - Latest Blogs - Excel Blog

الثلاثاء، 17 يناير 2023

vba code to highligt row and column in the selected cell and when move to another cell change the color of the last highligt to previous color


vba code to highligt row and column in the selected cell and when move to another cell change the color of the last highligt  to previous color




Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    ' Store the last selected cell and its row and column

    Static lastRow As Long, lastCol As Long

    Static lastColor As Long, lastFormat As String

    ' Remove highlighting from last selected cell and restore original format

    If lastRow <> 0 And lastCol <> 0 Then

        Rows(lastRow).Interior.Color = lastColor

        Columns(lastCol).NumberFormat = lastFormat

    End If

    ' Store the original format and color of the current selected cell

    lastColor = Target.EntireRow.Interior.Color

    lastFormat = Target.EntireColumn.NumberFormat

    ' Highlight the current selected cell's row and column

    Target.EntireRow.Interior.Color = RGB(255, 255, 0)

    Target.EntireColumn.NumberFormat = "Text"

    ' Store the current selected cell's row and column

    lastRow = Target.Row

    lastCol = Target.Column

End Sub

----------------------------------

This code uses the Worksheet_SelectionChange event to track when the user changes the selected cell. The Target parameter of the event contains the range of the new selection. When the user changes the selection, the code checks if there is a previous selection, and if so, changes the color of the previous selection back to its original color using the EntireRow and EntireColumn properties of the range, and Interior.ColorIndex or Interior.Color properties. Then it highlights the new selection and set the previous selection to the current selection.

You can also change the color to any color you want by changing the value of RGB function, for example if you want to change the color to red : RGB(255,0,0)

You can also change the color index of the cell by using the xlColorIndex instead of xlNone and RGB(255,255,0)

Please note that this code should be placed in the worksheet code module of the worksheet you want to use it on.


-------------




ليست هناك تعليقات:

إرسال تعليق