当插入行时,也会触发macros“触发单元更改”

我正在使用VBA来检查某个列中的单元格何时发生更改,因此可以调用另一个macros来对它们进行sorting。 这是奇妙的,除了它也会触发,每当我插入一个新的行。 因此,使用IsEmpty我添加了一个检查,看看有问题的单元格是不是空的。 但我显然做错了,因为我插入一行时,我的macros仍然被调用。 我究竟做错了什么?

触发单元格更改的VBA:

Private Sub Worksheet_Change(ByVal Target As Range) Dim KeyCells As Range Set KeyCells = Range("A:A") If Not Application.Intersect(KeyCells, Range(Target.Address)) _ Is Nothing Then If Not IsEmpty(KeyCells) Then Call SortByDate End If End If End Sub 

您可以通过检查接收到更改的单元的数量来过滤行插入。 在行插入的情况下,这大于或等于工作表的columns.count 。 如果您正在更改该工作表上的任何内容,请在开始更改任何内容之前使用application.enableevents = false ,并在离开子表单之前使用application.enableevents = false

 Private Sub Worksheet_Change(ByVal Target As Range) ' exit immediately on row insertion If Target.CountLarge >= Columns.Count Then Exit Sub If Not Intersect(Target, Columns(1)) Is Nothing Then 'escape route On Error GoTo bm_Safe_Exit 'don't declare or Set anything until you know you will need it '(this isn't really terribly necessary) Dim KeyCells As Range Set KeyCells = Range("A:A") If Application.CountA(KeyCells) Then 'is there ANYTHING in A:A? Application.EnableEvents = False Call SortByDate End If End If bm_Safe_Exit: Application.EnableEvents = True End Sub 

无法禁用事件处理并随后更改工作表上的任何内容将触发另一个更改事件,而Worksheet_Change事件macros将尝试在其本身之上运行。