有效vba范围

Effective vba range

下面是运行,但我只希望这个有效,例如sheet一个上的B10到H13。有没有简单的方法来选择vba的范围? 通常 Excel 会提供范围按钮,但我相信在这种情况下不会。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
       Cancel = True
    Worksheet_SelectionChange Target

End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'If the target cell is clear
     If Target.Interior.ColorIndex = xlNone Then

        'Then change the background to the specified color
        Target.Interior.ColorIndex = 4

        'But if the target cell is already the specified color
        ElseIf Target.Interior.ColorIndex = 4 Then

        'Then change the background to the specified color
        Target.Interior.ColorIndex = 3

        'But if the target cell is already the specified color
        ElseIf Target.Interior.ColorIndex = 3 Then

        'Then clear the background color
        Target.Interior.ColorIndex = xlNone

    End If
End Sub

已编辑...不确定这是否正是您所追求的,但它应该会给您一个良好的开端。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
       Cancel = True
    Worksheet_SelectionChange Target

End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'If the target cell is within the range
    If Not Application.Intersect(Target, Range("B10:H13")) Is Nothing Then

        'If the target cell is clear
         If Target.Interior.ColorIndex = xlNone Then

            'Then change the background to the specified color
            Target.Interior.ColorIndex = 4

            'But if the target cell is already the specified color
            ElseIf Target.Interior.ColorIndex = 4 Then

            'Then change the background to the specified color
            Target.Interior.ColorIndex = 3

            'But if the target cell is already the specified color
            ElseIf Target.Interior.ColorIndex = 3 Then

            'Then clear the background color
            Target.Interior.ColorIndex = xlNone

        End If
    End If
End Sub

不确定它是否是你想要的,但如果目标不在 B10:H13 范围内,你可以使用以下代码退出 sub:

    If Intersect(Target, Range("B10:H13")) Is Nothing Then Exit Sub