微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何区分触发工作表更改事件的不同动作

如何解决如何区分触发工作表更改事件的不同动作

我对单元格进行了验证,当输入中断验证时,会弹出一个消息框。

为了避免复制粘贴数据中断验证,我使用宏来验证粘贴数据。

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Cell As Range
    Dim KeyCells As Range
    Dim ValidCells As Range
    Dim Fail As Boolean
    
    Let Fail = False
    Set KeyCells = Range("A2:D2000")
    Set ValidCells = Application.Intersect(Target,KeyCells)

    If Not ValidCells Is nothing Then
        For Each Cell In ValidCells
            If Not Cell.Validation.Value Then
                Cell.Interior.Color = RGB(255,0)
                Let Fail = True
            Else
                Cell.Interior.Color = xlNone
            End If
        Next
        
        If Fail Then
            MsgBox "Please rectify the red background data"
        End If
    End If
End Sub

这在复制粘贴数据时效果很好。除非输入错误数据,否则会弹出很多MsgBox(由Validation 和Macro 触发)。

有没有办法区分什么动作触发了更改事件,所以我可以选择是否需要在宏中显示MsgBox

解决方法

为了使您的代码在没有验证值的情况下为 cel 内部着色,请尝试下一个方法:

Option Explicit
Private boolEv As Boolean

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.count > 1 Then Exit Sub
    If Not Intersect(Target,Range("A2:D2000")) Is Nothing Then
        Application.EnableEvents = False
        If Not Target.Validation.Value Then
            If Not boolEv Then
                Target.Interior.Color = RGB(255,0)
                MsgBox "rectify": boolEv = True
            Else
                boolEv = False
            End If
        Else
            Target.Interior.Color = xlNone
        End If
        Application.EnableEvents = True
    End If
End Sub

Boolean 变量是必需的,因为在初始单元格为空的情况下,事件会被触发两次。首先是接受的值(按 Cancel),其次是回到初始值(空)。这样就跳过了第二个(寄生)事件...

使用 If Target.value = "" then Exit Sub 不会让事件为单元格内部着色并发送消息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。