I got the following macro in my workbook:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Clear the color of all the cells
Cells.Interior.ColorIndex = 0
If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub
Application.ScreenUpdating = False
With ActiveCell
' Highlight the row and column that contain the active cell, within the current region
Range(Cells(.Row, .CurrentRegion.Column), Cells(.Row, .CurrentRegion.Columns.Count + .CurrentRegion.Column - 1)).Interior.ColorIndex = 8
Range(Cells(.CurrentRegion.Row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.Row - 1, .Column)).Interior.ColorIndex = 8
End With
Application.ScreenUpdating = True
End Sub
But I would like it to work just on the cells F8:IR254
, which is a region matrix.
Currently it works in every cell which contains a region name, also outside the matrix.
Would that be possible?
Thanks in advance.
Kind regards, S
Yes, it is possible.
You must add those lines of code at the beginning of your Sub:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rng As Range: Set rng = Range("F8:IR254")
If intersect(Target, rng) Is Nothing Then Exit Sub
You must use the function Application.Intersect()
to know if two (or more) ranges have a common part or not.
Please find your amended code :
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub
If Not Application.Intersect(Target, Me.Range("F8:IR254")) Is Nothing Then
'Clear the color of all the cells
Cells.Interior.ColorIndex = 0
Application.ScreenUpdating = False
With ActiveCell
' Highlight the row and column that contain the active cell, within the current region
Range(Cells(.Row, .CurrentRegion.Column), Cells(.Row, .CurrentRegion.Columns.Count + .CurrentRegion.Column - 1)).Interior.ColorIndex = 8
Range(Cells(.CurrentRegion.Row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.Row - 1, .Column)).Interior.ColorIndex = 8
End With
Application.ScreenUpdating = True
Else
'Outside of matrix
End If
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.