vba - 插入行时也会触发宏 "trigger on cell change"

标签 vba excel

我目前正在使用 VBA 检查某个列中的单元格何时更改,因此我可以调用不同的宏对它们进行排序。这非常有效,除了它在我插入新行时也会触发。所以使用 IsEmpty 我添加了一个检查以查看有问题的单元格是否不为空。但我显然做错了,因为每当我插入一行时,我的宏仍然会被调用。我究竟做错了什么?

在单元格更改时触发的 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 = true 之前在离开潜艇之前。

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事件宏将尝试在自身之上运行。

关于vba - 插入行时也会触发宏 "trigger on cell change",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33563198/

相关文章:

名称框中的 Excel 图表名称

c# - 激活状态栏中的 Num Lock 指示灯

arrays - 数组未从 For Loop VBA 填充

vba - 工作表更改事件在函数更新时触发,但在工作表更改时不触发

VBA:选择事件Word文档

loops - Excel宏: How to loop a chart making macro through a specific column every time the name in that column changes

vba - 在多个条件下执行

vba - 用 Unicode 代码替换字符的宏仅部分工作

vba - VBA-错误时转到ToErHandler :

excel - 从项目集合中调用项目