Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the old value of a changed cell in Excel VBA?

Tags:

excel

vba

I'm detecting changes in the values of certain cells in an Excel spreadsheet like this...

Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim old_value As String
Dim new_value As String

For Each cell In Target

    If Not (Intersect(cell, Range("cell_of_interest")) Is Nothing) Then
        new_value = cell.Value
        old_value = ' what here?
        Call DoFoo (old_value, new_value)
    End If

Next cell

End Sub

Assuming this isn't too bad a way of coding this, how do I get the value of the cell before the change?

like image 526
Brian Hooper Avatar asked Jan 12 '11 11:01

Brian Hooper


People also ask

How do I run VBA code when cell value changes?

Run Macro When a Cell Changes (Method 1)Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code.


3 Answers

try this

declare a variable say

Dim oval 

and in the SelectionChange Event

Public Sub Worksheet_SelectionChange(ByVal Target As Range) oval = Target.Value End Sub 

and in your Worksheet_Change event set

old_value = oval 
like image 116
Binil Avatar answered Sep 19 '22 01:09

Binil


You can use an event on the cell change to fire a macro that does the following:

vNew = Range("cellChanged").value Application.EnableEvents = False Application.Undo vOld = Range("cellChanged").value Range("cellChanged").value = vNew Application.EnableEvents = True  
like image 44
RonnieDickson Avatar answered Sep 23 '22 01:09

RonnieDickson


I had to do it too. I found the solution from "Chris R" really good, but thought it could be more compatible in not adding any references. Chris, you talked about using Collection. So here is another solution using Collection. And it's not that slow, in my case. Also, with this solution, in adding the event "_SelectionChange", it's always working (no need of workbook_open).

Dim OldValues As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    '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)
    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
        Debug.Print "New value of " & c.Address & " is " & 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
like image 20
Matt Roy Avatar answered Sep 23 '22 01:09

Matt Roy