首页 > 解决方案 > 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

标签: excelvba

解决方案


When your code selects a cell, that also triggers the event handler. Typically you would prevent that by setting Application.EnableEvents = False (don't forget to set it back to True later...) –</p>


推荐阅读