更改旧值和新值

时间:2013-10-09 11:32:47

标签: vba excel-vba selectionchanged excel

我有这个代码用于调用旧值和新值。但是我现在遇到一个问题,如果用户只是突出显示并点击删除它将运行并注意到更改,但是由于某种原因它会运行同一个请求的更多实例。有没有办法让它只运行一次? 感谢

Public OldValues As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Sheets("Pagination").Range("J11") <> "Yes" Then Exit Sub

    'Copy old values
    Set OldValues = Nothing
    Dim c As Range
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

If Sheets("Pagination").Range("J11") <> "Yes" Then Exit Sub

    On Local Error Resume Next  ' To avoid error if the old value of the cell address you're looking for has not been copied
    Dim c As Range
    For Each c In Target
        Sheets("corrections").Cells(Rows.Count, "A").End(xlUp)(2).Value = Now & " Sheet " & ActiveSheet.Name & " Cell " & Target.Address(0, 0) & " has a new value of " & c.Value & "; old value was " & OldValues(c.Address)
    Next c
    'Copy old values (in case you made any changes in previous lines of code)
    Set OldValues = Nothing
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub

1 个答案:

答案 0 :(得分:1)

Application.EnableEvents = False添加到Worksheet_Change事件的开头,然后返回到结尾的Application.EnableEvents = True

编辑:我无法自己重新创建您的问题,并且因为宏没有在同一张纸上进行更改,所以上述解决方案不应该有所作为。您是否在“更正”表上还有其他Worksheet_Change个事件需要禁用此类事件?


Application.EnableEvents也应添加到其他功能中 这可能会影响具有worksheet_change事件的工作表中的任何单元格。

例如,即使Cell A1的值发生更改,也会调用worksheet_change事件。