无限循环与target.address

我正在创build一个小程序,它将查找“当前”表中第I列的更改。 如果find更改,则会剪切并将整列粘贴到“完成”工作表的最后一行。 看起来,当它切割时,它会陷入一个无限循环,导致它永远不会popup消息框“Made it”。 我怎样才能重新certificate这个地址,以避免这个问题呢?

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 

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

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

 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