Excel VBA脚本循环无法正常工作

时间:2019-03-01 06:16:34

标签: excel vba

当B21为空白并且我单击D21单元格时,显示错误2和错误1(这是不期望的,因为我只期望错误1)。但是,当我单击E21单元格时,只会显示预期的错误2。

我不确定我要去哪里错了?

我的代码如下:

If [B21] = "" Then
    If Target.Column = 4 Then
         If Target.Row = 21 Then
            Beep
            Cells(Target.Row, Target.Column).Offset(0, 1).Select
            MsgBox "1.Error"
         End If
    ElseIf Target.Column = 5 Then
        If Target.Row = 21 Then
            Beep
            Cells(Target.Row, Target.Column).Offset(0, 1).Select
            MsgBox "2.Error"
        End If
    End If

2 个答案:

答案 0 :(得分:0)

当代码选择一个单元格时,也会触发事件处理程序。通常,您可以通过设置Application.EnableEvents = False来避免这种情况(不要忘记稍后将其设置回True ...)–

答案 1 :(得分:0)

蒂姆·威廉姆斯(Tim Williams)解决方案的替代方法是工作表范围的变量,以跟踪代码本身何时选择E21单元格

因此您的工作表代码为:

    Dim dontBeep As Boolean

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If [B21] = "" Then
        If Target.Column = 4 Then
             If Target.Row = 21 Then
                Beep
                dontBeep = True ' make sure subsequent E21 cell selection would not trigger any beep and action
                Target.Offset(0, 1).Select
                MsgBox "1.Error"
             End If
        ElseIf Target.Column = 5 Then
            If Target.Row = 21 Then
                If dontBeep Then
                    dontBeep = False ' restore default triggering conditions
                Else
                    Beep
                    Target.Offset(0, 1).Select
                    MsgBox "2.Error"
                End If
            End If
        End If
    End If

End Sub

您还可以在开始时进行行索引检查,因为两个相关列都相同:

Dim dontBeep As Boolean

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If [B21] = "" Then
        If Target.Row = 21 Then
            If Target.Column = 4 Then
               Beep
               dontBeep = True ' make sure subsequent E21 cell selection would not trigger any beep and action

               Target.Offset(0, 1).Select
               MsgBox "1.Error"
            ElseIf Target.Column = 5 Then
                If dontBeep Then
                    dontBeep = False
                Else
                    Beep' restore default triggering conditions
                    Target.Offset(0, 1).Select
                    MsgBox "2.Error"
                End If
            End If
        End If
    End If

End Sub