有效的vba范围

时间:2015-10-06 14:43:43

标签: vba range

下面是正在运行的内容,但我只希望这个有效,例如第一张上的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

2 个答案:

答案 0 :(得分:0)

已编辑...不确定这是否完全符合您的要求,但它应该会给您一个良好的开端。

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

答案 1 :(得分:0)

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

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