简体   繁体   中英

Highlighting rows and columns by ActiveCell in Excel VBA

My goal is create a VBA macro which highlights rows and columns by ActiveCell , so I programmed the following code:

Function Col_Letter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function

Public Sub SetCellPosition()
    Dim currentActiveCellAdress, columnLetter, rowRangeAddress, columnRangeAddress, selectionRangeAdress As String
    Dim rowNumber As Long

    columnLetter = Col_Letter(ActiveCell.Column)
    rowNumber = ActiveCell.Row

    rowRangeAddress = columnLetter & "1:" & columnLetter & rowNumber
    columnRangeAddress = "A" & rowNumber & ":" & columnLetter & rowNumber
    currentActiveCellAdress = ActiveCell.Address
    selectionRangeAdress = rowRangeAddress & ", " & columnRangeAddress

    Debug.Print selectionRangeAdress
    Debug.Print currentActiveCellAdress

    Range(selectionRangeAdress).Select
    Range(currentActiveCellAdress).Activate

End Sub

That macro works well. But after calling that macro by Workbook_SheetSelectionChange

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    Call SetCellPosition
End Sub

it gives me an error, selection in sheet flashes between highlighting rows and columns by ActiveCell and first row, please see the pictures.

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

The macro can be downloaded here .

Kind regards.

Jan

Your issue is that you call this macro in a SelectionChange event. However this line:

Range(selectionRangeAdress).Select

Counts as a SelectionChange event, meaning it will call this macro. This means you call this macro within the macro, resulting in a recursive function until you run out of stack space and it errors out. To prevent this, add Application.EnableEvents = False at the start, and True at the end. This prevents any events firing while the macro runs, thus preventing the function to call itself in the middle of it.

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Application.EnableEvents = False
    Call SetCellPosition
Application.EnableEvents = True
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM