带有target.address的无限循环

时间:2017-06-12 16:26:56

标签: excel vba access-vba

我正在创建一个小程序,它将在工作表" current"中寻找第I列的更改。如果找到了更改,它将剪切并将整个列粘贴到工作表的最后一行中#34;已完成"。似乎当它进行切割时,它会陷入无限循环,导致它永远不会碰到消息框"制造它。"。如何重新证明地址的合理性,以避免这个问题?

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Dim LastRowCompleted As Long
    LastRowCompleted = Sheets("completed").Cells(Sheets("completed").Rows.Count, "A").End(xlUp).Row
    LastRowCompleted = LastRowCompleted + 1 'Next row after last row

    Set KeyCells = Range("I:I")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then

        MsgBox "Cell " & Target.Address & " has changed."
        MsgBox Range(Target.Address).Row
        MsgBox Range(Target.Address).Column

        'Cut and Paste Row
        Range(Range(Target.Address).Row & ":" & Range(Target.Address).Row).Cut Sheets("completed").Range(LastRowCompleted & ":" & LastRowCompleted)
        MsgBox "Made it."
    End If
End Sub

1 个答案:

答案 0 :(得分:2)

如果要更改代码中的单元格内容,则使用“纸张更改”事件始终禁用事件,否则将在工作表上每次更改时重复触发更改事件。

要禁用事件,请在代码开头使用以下行

Application.EnableEvents = False

然后不要忘记最后启用该事件,否则任何事件代码都不会自动触发。

要启用事件,请在End Sub。

之前使用以下行
Application.EnableEvents = True

所以你的代码应该是这样的......

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Dim LastRowCompleted As Long
    LastRowCompleted = Sheets("completed").Cells(Sheets("completed").Rows.Count, "A").End(xlUp).Row
    LastRowCompleted = LastRowCompleted + 1 'Next row after last row

    Set KeyCells = Range("I:I")
    Application.EnableEvents = False
    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then

        MsgBox "Cell " & Target.Address & " has changed."
        MsgBox Range(Target.Address).Row
        MsgBox Range(Target.Address).Column

        'Cut and Paste Row
        Range(Range(Target.Address).Row & ":" & Range(Target.Address).Row).Cut Sheets("completed").Range(LastRowCompleted & ":" & LastRowCompleted)
        MsgBox "Made it."
    End If
    Application.EnableEvents = True
End Sub