宏仅针对特定细胞范围

时间:2015-07-17 08:34:30

标签: excel vba excel-vba

我的工作簿中有以下宏:

Integer.valueOf(1)

但是我希望它只能在单元格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 上工作,这是一个区域矩阵。

目前它适用于包含区域名称的每个单元格,也在矩阵之外。

这可能吗?

提前致谢。

亲切的问候, S

2 个答案:

答案 0 :(得分:1)

是的,这是可能的。

您必须在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

答案 1 :(得分:0)

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

请找到修改后的代码:

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