Ga naar hoofdinhoud

Hoe kan ik de vorige celwaarde van een gewijzigde cel in Excel onthouden of opslaan?

Normaal gesproken wordt bij het bijwerken van een cel met nieuwe inhoud de vorige waarde gedekt, tenzij de bewerking in Excel ongedaan wordt gemaakt. Als u echter de vorige waarde wilt behouden om te vergelijken met de bijgewerkte, is het een goede keuze om de vorige celwaarde in een andere cel of in de celopmerking op te slaan. De methode in dit artikel zal u helpen om dit te bereiken.

Sla de vorige celwaarde op met VBA-code in Excel


Sla de vorige celwaarde op met VBA-code in Excel

Stel dat u een tabel heeft zoals hieronder afgebeeld. Als een cel in kolom C is gewijzigd, wilt u de vorige waarde opslaan in de overeenkomstige cel van kolom G of automatisch opslaan in commentaar. Ga als volgt te werk om dit te bereiken.

1. Bevat in het werkblad de waarde die u bij het bijwerken opslaat, klik met de rechtermuisknop op de bladtab en selecteer Bekijk code vanuit het rechtsklikmenu. Zie screenshot:

2. In de opening Microsoft Visual Basic voor toepassingen -venster, kopieer de onderstaande VBA-code naar het codevenster.

De volgende VBA-code helpt u de vorige celwaarde van de opgegeven kolom op te slaan in een andere kolom.

VBA-code: sla de vorige celwaarde op in een andere kolomcel

Dim xRg As Range
Dim xChangeRg As Range
Dim xDependRg As Range
Dim xDic As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Long
    Dim xCell As Range
    Dim xDCell As Range
    Dim xHeader As String
    Dim xCommText As String
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    xHeader = "Previous value :"
    x = xDic.Keys
    For I = 0 To UBound(xDic.Keys)
        Set xCell = Range(xDic.Keys(I))
        Set xDCell = Cells(xCell.Row, 7)
        xDCell.Value = ""
        xDCell.Value = xDic.Items(I)
    Next
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim I, J As Long
    Dim xRgArea As Range
    On Error GoTo Label1
    If Target.Count > 1 Then Exit Sub
    Application.EnableEvents = False
    Set xDependRg = Target.Dependents
    If xDependRg Is Nothing Then GoTo Label1
    If Not xDependRg Is Nothing Then
        Set xDependRg = Intersect(xDependRg, Range("C:C"))
    End If
Label1:
    Set xRg = Intersect(Target, Range("C:C"))
    If (Not xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = Union(xRg, xDependRg)
    ElseIf (xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = xDependRg
    ElseIf (Not xRg Is Nothing) And (xDependRg Is Nothing) Then
        Set xChangeRg = xRg
    Else
        Application.EnableEvents = True
        Exit Sub
    End If
    xDic.RemoveAll
    For I = 1 To xChangeRg.Areas.Count
        Set xRgArea = xChangeRg.Areas(I)
        For J = 1 To xRgArea.Count
            xDic.Add xRgArea(J).Address, xRgArea(J).Formula
        Next
    Next
    Set xChangeRg = Nothing
    Set xRg = Nothing
    Set xDependRg = Nothing
    Application.EnableEvents = True
End Sub

Pas de onderstaande VBA-code toe om de vorige celwaarde in een opmerking op te slaan

VBA-code: sla de vorige celwaarde op in de opmerking

Dim xRg As Range
Dim xChangeRg As Range
Dim xDependRg As Range
Dim xDic As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Long
    Dim xCell As Range
    Dim xHeader As String
    Dim xCommText As String
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    xHeader = "Previous value :"
    For I = 0 To UBound(xDic.Keys)
        Set xCell = Range(xDic.Keys(I))
        If Not xCell.Comment Is Nothing Then xCell.Comment.Delete
        With xCell
            .AddComment
            .Comment.Visible = False
            .Comment.Text xHeader & vbCrLf & xDic.Items(I)
        End With
    Next
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim I, J As Long
    Dim xRgArea As Range
    On Error GoTo Label1
    If Target.Count > 1 Then Exit Sub
    Application.EnableEvents = False
    Set xDependRg = Target.Dependents
    If xDependRg Is Nothing Then GoTo Label1
    If Not xDependRg Is Nothing Then
        Set xDependRg = Intersect(xDependRg, Range("C:C"))
    End If
Label1:
    Set xRg = Intersect(Target, Range("C:C"))
    If (Not xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = Union(xRg, xDependRg)
    ElseIf (xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = xDependRg
    ElseIf (Not xRg Is Nothing) And (xDependRg Is Nothing) Then
        Set xChangeRg = xRg
    Else
        Application.EnableEvents = True
        Exit Sub
    End If
    xDic.RemoveAll
    For I = 1 To xChangeRg.Areas.Count
        Set xRgArea = xChangeRg.Areas(I)
        For J = 1 To xRgArea.Count
            xDic.Add xRgArea(J).Address, xRgArea(J).Text
        Next
    Next
    Set xChangeRg = Nothing
    Set xRg = Nothing
    Set xDependRg = Nothing
    Application.EnableEvents = True
End Sub

Note: In de code geeft nummer 7 de kolom G aan waarin u de vorige cel wilt opslaan, en C: C is de kolom waarin u de vorige celwaarde wilt opslaan. Wijzig ze op basis van uw behoeften.

3. klikken Tools > Referenties om de te openen Refereces - VBAProject dialoogvenster, controleer de Microsoft Scripting-runtime vak en klik ten slotte op het OK knop. Zie screenshot:

4. druk de anders + Q toetsen om de Microsoft Visual Basic voor toepassingen venster.

Vanaf nu, wanneer de celwaarde in kolom C wordt bijgewerkt, wordt de vorige waarde van de cel opgeslagen in de corresponderende cellen in kolom G of opgeslagen in commentaar zoals hieronder weergegeven screenshots.

Bewaar vorige celwaarden in andere cellen:

Bewaar eerdere celwaarden in opmerkingen:

Beste Office-productiviteitstools

🤖 Kutools AI-assistent: Een revolutie teweegbrengen in de data-analyse op basis van: Intelligente uitvoering   |  Genereer code  |  Aangepaste formules maken  |  Analyseer gegevens en genereer grafieken  |  Roep Kutools-functies aan...
Populaire functies: Zoek, markeer of identificeer duplicaten   |  Verwijder lege rijen   |  Combineer kolommen of cellen zonder gegevens te verliezen   |   Ronde zonder formule ...
Super opzoeken: Meerdere criteria VLookup    VLookup met meerdere waarden  |   VOpzoeken over meerdere bladen   |   Fuzzy opzoeken ....
Geavanceerde vervolgkeuzelijst: Maak snel een vervolgkeuzelijst   |  Afhankelijke vervolgkeuzelijst   |  Multi-select vervolgkeuzelijst ....
Kolom Beheerder: Voeg een specifiek aantal kolommen toe  |  Kolommen verplaatsen  |  Schakel de zichtbaarheidsstatus van verborgen kolommen in  |  Vergelijk bereiken en kolommen ...
Uitgelichte functies: Raster focus   |  Ontwerpweergave   |   Grote formulebalk    Werkmap- en bladbeheer   |  resource Library (Auto-tekst)   |  Datumkiezer   |  Combineer werkbladen   |  Cellen coderen/decoderen    Stuur e-mails per lijst   |  Super filter   |   Speciaal filter (filter vet/cursief/doorhalen...) ...
Top 15 gereedschapsets12 Tekst Tools (toe te voegen tekst, Tekens verwijderen, ...)   |   50+ tabel Types (Gantt Chart, ...)   |   40+ Praktisch Formules (Bereken leeftijd op basis van verjaardag, ...)   |   19 Invoeging Tools (QR-code invoegen, Afbeelding invoegen vanaf pad, ...)   |   12 Camper ombouw Tools (Getallen naar woorden, Currency Conversion, ...)   |   7 Samenvoegen en splitsen Tools (Geavanceerd Combineer rijen, Gespleten cellen, ...)   |   ... en meer

Geef uw Excel-vaardigheden een boost met Kutools voor Excel en ervaar efficiëntie als nooit tevoren. Kutools voor Excel biedt meer dan 300 geavanceerde functies om de productiviteit te verhogen en tijd te besparen.  Klik hier om de functie te krijgen die u het meest nodig heeft...

Omschrijving


Office-tabblad Brengt een interface met tabbladen naar Office en maakt uw werk veel gemakkelijker

  • Schakel bewerken en lezen met tabbladen in Word, Excel, PowerPoint in, Publisher, Access, Visio en Project.
  • Open en maak meerdere documenten in nieuwe tabbladen van hetzelfde venster in plaats van in nieuwe vensters.
  • Verhoogt uw productiviteit met 50% en vermindert honderden muisklikken voor u elke dag!
Comments (23)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hi, I'm a newbie of VBA👋

I have a question here 🧐
I pasted the VBA code: Save previous cell value in the comment I my excel but
What if my previous cell is blank then do nothing (No comment) for that particular BLANK cell?
How do I modify the VBA code?
Any expert to provide any solution of this, many thanks👋
This comment was minimized by the moderator on the site
Hi!

Thank you for the function, i would like to know what i have to change to keep all the change.

For exemple if i change two time the value i want te save both last values.

Thank you in advance for the help!
This comment was minimized by the moderator on the site
Hi,
The following VBA code accomplishes this: Track all changes in Column C and store the previous values in successive columns starting from Column G. If Column G is not where you want to start storing these values, adjust the xColumn = 7 line in the code (7 represents Column G, 8 for Column H, and so on).
Hope I can help.

Dim xRg As Range
Dim xChangeRg As Range
Dim xDependRg As Range
Dim xDic As New Dictionary

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by extendoffice 20240112
    Dim xCell As Range
    Dim xPrevCell As Range
    Dim xColumn As Long
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    For Each xCell In Target
        If Not xDic.Exists(xCell.Address) Then GoTo NextCell
        If Intersect(xCell, Me.Range("C:C")) Is Nothing Then GoTo NextCell

        ' Find next available column starting from G
        xColumn = 7
        While Me.Cells(xCell.Row, xColumn).Value <> ""
            xColumn = xColumn + 1
        Wend

        ' Save previous value to the next available column
        Set xPrevCell = Me.Cells(xCell.Row, xColumn)
        xPrevCell.Value = xDic(xCell.Address)

NextCell:
    Next xCell

    ' Clear the dictionary and re-enable events
    xDic.RemoveAll
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    On Error GoTo 0
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim cell As Range
    On Error Resume Next
    Application.EnableEvents = False

    ' Reset dictionary and store current values for cells in column C
    xDic.RemoveAll
    For Each cell In Intersect(Target, Me.Range("C:C"))
        If Not cell Is Nothing Then
            xDic.Add cell.Address, cell.Value
        End If
    Next cell

    Application.EnableEvents = True
    On Error GoTo 0
End Sub
This comment was minimized by the moderator on the site
Can any body help in this problem
This comment was minimized by the moderator on the site
saving the previous data when entering manually but not working when data is refreshing from a web site, it is doing nothing
please help
thanks
This comment was minimized by the moderator on the site
Hi Kamal.
This problem is a bit complicated. After trying various methods, I can't deal with it. I am sorry for that.
This comment was minimized by the moderator on the site
only working when entering data manually
but not working when data is refreshing from a website
please help
thanks
This comment was minimized by the moderator on the site
cho e hỏi chút là có cách nào để khi tính toán cộng trừ xong thì nó sẽ lưu lại giá trị khi tính toán xong không ạ
ví dụ:
Giá trị ở cột A = cột B + cột C
Khi tính toán xong cột A sẽ lưu giá trị sau khi đã tính toán xong, lần tiếp theo tính toán thì nó cột A sẽ lấy giá trị hiện tại để tính toán tiếp chứ không lấy giá trị ban đầu ạ
This comment was minimized by the moderator on the site
Hi trung,
The code has been updated. Please give it a try. Thanks for your feedback.
In the following code, the number 5 in this line Set xDCell = Cells(xCell.Row, 5) represents the column E where you will place the previous value. A:A refers to the cells in column A. You need to save the previous values of these cells.

Dim xRg As Range
'Updated by Extendoffice 20220803
Dim xChangeRg As Range
Dim xDependRg As Range
Dim xDic As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Long
    Dim xCell As Range
    Dim xDCell As Range
    Dim xHeader As String
    Dim xCommText As String
    Dim X
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    xHeader = "Previous value :"
    X = xDic.Keys
    For I = 0 To UBound(xDic.Keys)
        Set xCell = Range(xDic.Keys(I))
        Set xDCell = Cells(xCell.Row, 5)
        
        xDCell.NumberFormatLocal = xCell.NumberFormatLocal
        xDCell.Value = xDic.Items(I)
        
    Next
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim I, J As Long
    Dim xRgArea As Range
    On Error GoTo Label1
    If Target.Count > 1 Then Exit Sub
    Application.EnableEvents = False
    Set xDependRg = Target.Dependents
    If xDependRg Is Nothing Then GoTo Label1
    If Not xDependRg Is Nothing Then
        Set xDependRg = Intersect(xDependRg, Range("A:A"))
    End If
Label1:
    Set xRg = Intersect(Target, Range("A:A"))
    If (Not xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = Union(xRg, xDependRg)
    ElseIf (xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = xDependRg
    ElseIf (Not xRg Is Nothing) And (xDependRg Is Nothing) Then
        Set xChangeRg = xRg
    Else
        Application.EnableEvents = True
        Exit Sub
    End If
    xDic.RemoveAll
    For I = 1 To xChangeRg.Areas.Count
        Set xRgArea = xChangeRg.Areas(I)
        For J = 1 To xRgArea.Count
            xDic.Add xRgArea(J).Address, xRgArea(J).Text ' xRgArea(J).Formula
        Next
    Next
    Set xChangeRg = Nothing
    Set xRg = Nothing
    Set xDependRg = Nothing
    Application.EnableEvents = True
End Sub
This comment was minimized by the moderator on the site
It is good if you type in.Can you help me to work it in when data is entered by using the value of function from DDE(Dynamic Data Exchange) as well?
This comment was minimized by the moderator on the site
Hi,
Sorry I can't solve this problem. I suggest you post the problem to the forum below to get help from other Excel enthusiasts.
https://www.extendoffice.com/forum/kutools-for-excel.html
This comment was minimized by the moderator on the site
Is there a way to repeat this for all changes? I would like the Comments Box to show all of the previous entries if possible.
This comment was minimized by the moderator on the site
Hi Jennie! Did you manage to solve this issue? I am also trying to collect in a comments box all the new entries, but I am having difficulties to adapt the VBA code to this. Thank you!
This comment was minimized by the moderator on the site
If the cell I want to save is a formula, the G cell will only save the formula, and calculate the value. I need to save the value - not the formula. How can I tell the VBA code, that the value changes although the formula is not changed. Best regards Flemming
This comment was minimized by the moderator on the site
This is for one cell value ,but how do for multiple cell value ,i want 4 cell data store and update like this for example C,D,E,F cell data into G,H,I,J cell respectively ,how can do please help
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations