Przejdź do głównej zawartości

Jak zapamiętać lub zapisać poprzednią wartość komórki zmienionej komórki w programie Excel?

Zwykle podczas aktualizowania komórki o nową zawartość poprzednia wartość zostanie uwzględniona, chyba że cofniesz operację w programie Excel. Jeśli jednak chcesz zachować poprzednią wartość do porównania ze zaktualizowaną, dobrym wyborem będzie zapisanie poprzedniej wartości komórki w innej komórce lub w komentarzu do komórki. Pomoże Ci w tym metoda opisana w tym artykule.

Zapisz poprzednią wartość komórki za pomocą kodu VBA w programie Excel


Zapisz poprzednią wartość komórki za pomocą kodu VBA w programie Excel

Przypuśćmy, że masz tabelę pokazaną na poniższym zrzucie ekranu. Jeśli dowolna komórka w kolumnie C uległa zmianie, chcesz zapisać jej poprzednią wartość w odpowiedniej komórce kolumny G lub automatycznie zapisać komentarz. Aby to osiągnąć, wykonaj następujące czynności.

1. W arkuszu zawierającym wartość, którą zapiszesz podczas aktualizacji, kliknij prawym przyciskiem myszy kartę arkusza i wybierz Wyświetl kod z menu po kliknięciu prawym przyciskiem myszy. Zobacz zrzut ekranu:

2. W otwarciu Microsoft Visual Basic for Applications skopiuj poniższy kod VBA do okna Code.

Poniższy kod VBA pomaga zapisać poprzednią wartość komórki określonej kolumny w innej kolumnie.

Kod VBA: zapisz poprzednią wartość komórki w innej komórce kolumny

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

Aby zapisać poprzednią wartość komórki w komentarzu, zastosuj poniższy kod VBA

Kod VBA: zapisz poprzednią wartość komórki w komentarzu

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: W kodzie liczba 7 oznacza kolumnę G, w której zapiszesz poprzednią komórkę, a C: C to kolumna, w której zapiszesz poprzednią wartość komórki. Zmień je w zależności od potrzeb.

3. kliknij Tools > Referencje otworzyć Referencje - VBAProject w oknie dialogowym, sprawdź Środowisko wykonawcze skryptów firmy Microsoft Microsoft i na koniec kliknij OK przycisk. Zobacz zrzut ekranu:

4. wciśnij inny + Q klucze do zamknięcia Microsoft Visual Basic for Applications okno.

Odtąd, po zaktualizowaniu wartości komórki w kolumnie C, poprzednia wartość komórki zostanie zapisana w odpowiednich komórkach w kolumnie G lub zostanie zapisana w komentarzu, jak pokazano na poniższych zrzutach ekranu.

Zapisz poprzednie wartości komórek w innych komórkach:

Zapisz poprzednie wartości komórek w komentarzach:

Najlepsze narzędzia biurowe

🤖 Pomocnik AI Kutools: Zrewolucjonizuj analizę danych w oparciu o: Inteligentne wykonanie   |  Wygeneruj kod  |  Twórz niestandardowe formuły  |  Analizuj dane i generuj wykresy  |  Wywołaj funkcje Kutools...
Popularne funkcje: Znajdź, wyróżnij lub zidentyfikuj duplikaty   |  Usuń puste wiersze   |  Łącz kolumny lub komórki bez utraty danych   |   Okrągły bez wzoru ...
Super wyszukiwanie: Wiele kryteriów VLookup    Wiele wartości VLookup  |   Przeglądanie pionowe na wielu arkuszach   |   Wyszukiwanie rozmyte ....
Zaawansowana lista rozwijana: Szybko twórz listę rozwijaną   |  Zależna lista rozwijana   |  Lista rozwijana wielokrotnego wyboru ....
Menedżer kolumn: Dodaj określoną liczbę kolumn  |  Przesuń kolumny  |  Przełącz stan widoczności ukrytych kolumn  |  Porównaj zakresy i kolumny ...
Polecane funkcje: Fokus siatki   |  Widok projektu   |   Duży pasek formuły    Menedżer skoroszytów i arkuszy   |  Biblioteka zasobów (Automatyczny tekst)   |  Selektor dat   |  Połącz arkusze   |  Szyfruj/odszyfruj komórki    Wysyłaj e-maile według listy   |  Super filtr   |   Specjalny filtr (filtruj pogrubienie/kursywa/przekreślenie...) ...
15 najlepszych zestawów narzędzi12 Tekst Tools (Dodaj tekst, Usuń znaki, ...)   |   50 + Wykres rodzaje (Wykres Gantta, ...)   |   40+ Praktyczne Wzory (Oblicz wiek na podstawie urodzin, ...)   |   19 Wprowadzenie Tools (Wstaw kod QR, Wstaw obraz ze ścieżki, ...)   |   12 Konwersja Tools (Liczby na słowa, Przeliczanie walut, ...)   |   7 Połącz i podziel Tools (Zaawansowane wiersze łączenia, Podział komórki, ...)   |   ... i więcej

Zwiększ swoje umiejętności Excela dzięki Kutools for Excel i doświadcz wydajności jak nigdy dotąd. Kutools dla programu Excel oferuje ponad 300 zaawansowanych funkcji zwiększających produktywność i oszczędzających czas.  Kliknij tutaj, aby uzyskać funkcję, której najbardziej potrzebujesz...

Opis


Karta Office wprowadza interfejs z zakładkami do pakietu Office i znacznie ułatwia pracę

  • Włącz edycję i czytanie na kartach w programach Word, Excel, PowerPoint, Publisher, Access, Visio i Project.
  • Otwieraj i twórz wiele dokumentów w nowych kartach tego samego okna, a nie w nowych oknach.
  • Zwiększa produktywność o 50% i redukuje setki kliknięć myszką każdego dnia!
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