跳到主要內容

如何在Excel中記住或保存已更改單元格的先前單元格值?

通常,當用新內容更新單元格時,會覆蓋以前的值,除非在 Excel 中撤消操作。 但是,如果您想保留先前的值以與更新的值進行比較,將先前的單元格值保存到另一個單元格或單元格註釋中將是一個不錯的選擇。 本文中的方法將幫助您實現它。

在Excel中使用VBA代碼保存以前的單元格值


在Excel中使用VBA代碼保存以前的單元格值

假設您有一個表格,如下所示。 如果C列中的任何單元格發生更改,則要將其先前的值保存到G列的相應單元格中,或自動保存在註釋中。 請按照以下步驟進行操作。

1.在工作表中包含更新時將保存的值,右鍵單擊工作表選項卡,然後選擇 查看代碼 從右鍵單擊菜單中。 看截圖:

2.在開幕 Microsoft Visual Basic for Applications 窗口,將下面的VBA代碼複製到“代碼”窗口中。

以下VBA代碼可幫助您將指定列的先前單元格值保存到另一列中。

VBA代碼:將先前的單元格值保存到另一個列單元格中

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

要在註釋中保存以前的單元格值,請應用以下VBA代碼

VBA代碼:在註釋中保存以前的單元格值

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

備註:在代碼中,數字7表示將先前的單元格保存到的G列,而C:C是將先前的單元格值保存的列。 請根據您的需要進行更改。

3。 點擊 工具 > 參考 打開 裁判– VBAProject 對話框,檢查 Microsoft腳本運行時 框,最後單擊 OK 按鈕。 看截圖:

4。 按 其他 + Q 關閉鍵 Microsoft Visual Basic for Applications 窗口。

從現在開始,當C列中的單元格值更新時,該單元格的先前值將保存到G列中的相應單元格中,或保存在註釋中,如下面的屏幕快照所示。

將以前的單元格值保存在其他單元格中:

在註釋中保存以前的單元格值:

最佳辦公生產力工具

🤖 Kutools 人工智慧助手:基於以下內容徹底改變數據分析: 智慧執行   |  生成代碼  |  建立自訂公式  |  分析數據並產生圖表  |  呼叫 Kutools 函數...
熱門特色: 尋找、突出顯示或識別重複項   |  刪除空白行   |  合併列或儲存格而不遺失數據   |   沒有公式的回合 ...
超級查詢: 多條件VLookup    多值VLookup  |   跨多個工作表的 VLookup   |   模糊查詢 ....
高級下拉列表: 快速建立下拉列表   |  依賴下拉列表   |  多選下拉列表 ....
欄目經理: 新增特定數量的列  |  移動列  |  切換隱藏列的可見性狀態  |  比較範圍和列 ...
特色功能: 網格焦點   |  設計圖   |   大方程式酒吧    工作簿和工作表管理器   |  資源庫 (自動文字)   |  日期選擇器   |  合併工作表   |  加密/解密單元格    按清單發送電子郵件   |  超級濾鏡   |   特殊過濾器 (過濾粗體/斜體/刪除線...)...
前 15 個工具集12 文本 工具 (添加文本, 刪除字符,...)   |   50+ 圖表 類型 (甘特圖,...)   |   40+ 實用 公式 (根據生日計算年齡,...)   |   19 插入 工具 (插入二維碼, 從路徑插入圖片,...)   |   12 轉化 工具 (數字到單詞, 貨幣兌換,...)   |   7 合併與拆分 工具 (高級合併行, 分裂細胞,...)   |   ... 和更多

使用 Kutools for Excel 增強您的 Excel 技能,體驗前所未有的效率。 Kutools for Excel 提供了 300 多種進階功能來提高生產力並節省時間。  點擊此處獲取您最需要的功能...

產品描述


Office選項卡為Office帶來了選項卡式界面,使您的工作更加輕鬆

  • 在Word,Excel,PowerPoint中啟用選項卡式編輯和閱讀,發布者,Access,Visio和Project。
  • 在同一窗口的新選項卡中而不是在新窗口中打開並創建多個文檔。
  • 將您的工作效率提高 50%,每天為您減少數百次鼠標點擊!
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