选择更改影响范围之外的细胞

时间:2017-04-19 14:18:32

标签: excel excel-vba vba

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Const Col As Long = 2

    If Not Intersect(Target, Range("L7:L98")) Is Nothing Then
        Application.EnableEvents = False
        Target.Value = "T"
        Target.Offset(, 1).Resize(, Col).ClearContents
        Application.EnableEvents = True
    End If

    If Not Intersect(Target, Range("M7:M98")) Is Nothing Then
        Application.EnableEvents = False
        Target.Value = "I"
        Target.Offset(, 1).ClearContents
        Target.Offset(, -1).ClearContents
        Application.EnableEvents = True
    End If

    If Not Intersect(Target, Range("N7:N98")) Is Nothing Then
        Application.EnableEvents = False
        Target.Value = "D"
        Range(Target.Offset(, -1), Target.Offset(, -2)).ClearContents
        Application.EnableEvents = True
    End If

End Sub

此代码对我造成轻微问题。每当我在范围内选择整行时,范围内的每个单元格都会变为" T"。鉴于代码的一致性,如果我用" T"删除字符串,那么整行将填充" I"

如果选择范围内的单元格,可以调整什么来触发

2 个答案:

答案 0 :(得分:1)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Const Col As Long = 2

    If Target.Count > 1 Then
    Exit Sub
    End If

将此添加到代码顶部,如果选择了多个单元格,它现在将退出Sub,即使其中一个选定单元格在适当的范围内。

答案 1 :(得分:1)

在检查选择是否与各种范围相交之后,只处理与各种范围相交的Target部分。

MyCommand = new Command(async parameter => 
{
    IsPlaying = true;
    IsNotPlaying = false;
    await Task.Run(() => FilePreview?.FilePlayStart());
});

可选替代方案:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Const Col As Long = 2

    If Not Intersect(Target, Range("L7:L98")) Is Nothing Then
        Application.EnableEvents = False
        With Intersect(Target, Range("L7:L98"))
            .Value = "T"
            .Offset(, 1).Resize(, Col).ClearContents
        End With
    End If
    If Not Intersect(Target, Range("M7:M98")) Is Nothing Then
        Application.EnableEvents = False
        With Intersect(Target, Range("M7:M98"))
            .Value = "I"
            .Offset(, 1).Resize(, Col).ClearContents
        End With
    End If
    If Not Intersect(Target, Range("N7:N98")) Is Nothing Then
        Application.EnableEvents = False
        With Intersect(Target, Range("N7:N98"))
            .Value = "D"
            .Offset(, 1).Resize(, Col).ClearContents
        End With
    End If

    Application.EnableEvents = True

End Sub