只针对特定单元格范围的macros

我的工作簿中有以下macros:

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 

但是我希望它能在单元格F8:IR254 ,这是一个区域matrix。

目前它在包含区域名称的每个单元格中工作,也在matrix之外。

这可能吗?

提前致谢。

亲切的问候,S

对的,这是可能的。

你必须在你的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 

您必须使用函数Application.Intersect()来知道两个(或更多)范围是否具有公共部分。

请find您的修改代码:

 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