Vba突出显示双击单元格,第二次双击从2个范围中删除格式

时间:2016-07-21 09:35:28

标签: excel vba excel-vba

我有两个范围A1:A4和A5:A10。我希望能够突出显示一个单元格,当它从第一个范围双击时说A1,当我然后双击同一范围内的单元格时说A2这将取消高亮显示A1并突出显示A2。我想对第二个范围做同样的事情,但彼此独立,所以我最终会得到2个突出显示的单元格,每个范围一个。我目前使用的代码目前仅用于第二个范围:

Public PreviousCell As Range
Public PreviousCell2 As Range

Private Sub Worksheet_BeforeDoubleClick(ByVal target As Range, Cancel As Boolean)

If Not PreviousCell Is Nothing Then PreviousCell.Interior.ColorIndex = xlNone



With target.Interior
    If Not .ColorIndex = xlNone Then
        .ColorIndex = xlNone
    ElseIf Not Intersect(target, Range("A1:A4")) Is Nothing Then
        .ColorIndex = 15
    ElseIf Not .ColorIndex = 15 Then
        .ColorIndex = xlNone
    End If
End With
Cancel = True

Set PreviousCell = target

If Not PreviousCell2 Is Nothing Then PreviousCell2.Interior.ColorIndex = xlNone

With target.Interior
    If Not .ColorIndex = xlNone Then
        .ColorIndex = xlNone
    ElseIf Not Intersect(target, Range("A5:A10")) Is Nothing Then
        .ColorIndex = 15
    ElseIf Not .ColorIndex = 15 Then
        .ColorIndex = xlNone
    End If
End With
Cancel = True

Set PreviousCell2 = target

End Sub

谢谢!

2 个答案:

答案 0 :(得分:0)

好吧,我现在看到了这个问题。问题是您将前两个单元格值设置为target,无论选择的范围如何。只有在 相应范围发生变化时,您才需要将PreviousCellPreviousCell2更改为定位。因此,如果Target在A1:A4范围内,那么PreviousCell将会更改,如果Target在A5:A10范围内,则PreviousCell2应相应更改。

答案 1 :(得分:0)

如果在Range("A1:A4")中双击一个单元格,则清除整个范围内的颜色,然后突出显示目标范围。对Range("A5:A10")做同样的事。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    If Not Intersect(Target, Range("A1:A4")) Is Nothing Then
        Range("A1:A4").Interior.ColorIndex = xlNone
        Target.Interior.ColorIndex = 15
    ElseIf Not Intersect(Target, Range("A5:A10")) Is Nothing Then
        Range("A5:A10").Interior.ColorIndex = xlNone
        Target.Interior.ColorIndex = 15
    End If

End Sub