简体   繁体   中英

Save old value of a cell in VBA

I have create this macro finding pieces around and suiting it to my program:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("N19")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        Dim vNew As Integer
        Dim vOld As Integer
        vNew = Range("N19").Value
        Application.EnableEvents = False
        Application.Undo
        vOld = Range("N19").Value
        Range("N19").Value = vNew
        Range("D159").Value = vOld
        Application.EnableEvents = True

    End If
End Sub

I need to save the old value of N19 in D159.

Do you know why it is not working?

Thanks

You have to change the place of the assigning of value to vOld . In your code, it was assigned to N19 after the Application.Undo , thus it is assigned to nothing. I have tried this, it worked:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("N19")

    If Not Application.Intersect(KeyCells, Target) Is Nothing Then

        Dim vNew As Long
        Dim vOld As Long

        vNew = Range("N19")
        vOld = Range("N19")
        Application.EnableEvents = False
        Application.Undo
        vOld = Range("N19")
        Range("N19") = vNew
        Range("D159") = vOld

        Application.EnableEvents = True

    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM