将数据复制并粘贴到列中时不会触发 Vba Worksheet_Change 事件,但可以手动单击单元格

问题描述

我正在尝试用一段代码解决一个问题。我知道之前有人问过这个问题,但我无法让这些解决方案发挥作用。当我将数据复制并粘贴到 A 列时,以下工作表更改事件不会触发,但是当用户手动单击单元格时会触发,我该如何解决这个问题?

Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Range

 

   Application.EnableEvents = False

 

For Each cell In Target

If Not Application.Intersect(cell,Range("A7:A1048576")) Is nothing Then

If Not IsNumeric(cell.Value) Then

    cell.Value = vbNullString

    MsgBox ("Please re-enter,value entered contains non-numeric entry")

End If

End If

Next cell

 

If Not Intersect(Target,Range("A7:A1048576")) Is nothing Then

On Error Resume Next

If Target.Value = "" Or Target.Value = "0" Then

Target.Offset(0,12) = ""

Target.Offset(0,13) = ""

Else

Target.Offset(0,12).Value = Format(Now,"mm/dd/yyyy HH:mm:ss")

Target.Offset(0,13).Value = Environ("username")

 

End If

End If

    Application.EnableEvents = True

End Sub

解决方法

这段代码应该可以做你想做的事。请尝试一下。

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Cell As Range

    If Not Application.Intersect(Target,Range("A7:A1048576")) Is Nothing Then
        Set Target = Target.Columns(1)          ' remove all cells outside column A
        Application.EnableEvents = False
        
        For Each Cell In Target.Cells
            With Cell
                If .Value = "" Or .Value = 0 Then
                    .Offset(0,12).Resize(1,2).Value = vbNullString
                Else
                    If Not IsNumeric(.Value) Then
                        .Value = vbNullString
                        MsgBox ("Please re-enter,value entered contains non-numeric entry")
                        .Select
                        Exit For
                    Else
                        .Offset(0,12).Value = Format(Now,"mm/dd/yyyy HH:mm:ss")
                        .Offset(0,13).Value = Environ("username")
                    End If
                End If
            End With
        Next Cell
        
        Application.EnableEvents = True
    End If
End Sub

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...