显示单元格的旧值和新值

时间:2013-10-04 12:59:02

标签: excel vba excel-vba

我有一个工作表,记录了对单元格所做的更改。它如下

Public OldVal As String
Public NewVal As String


Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub
OldVal = Target.Value
End Sub


Private Sub Worksheet_Change(ByVal Target As Range)
Dim LDate As String

If Target.Cells.Count > 1 Then Exit Sub
NewVal = Target.Value
Sheets("corrections").Cells(Rows.Count, "A").End(xlUp)(2).Value = Now & "_Sheet " & ActiveSheet.Name & " Cell " & Target.Address(0, 0) & " was changed from '" & OldVal & "' to '" & NewVal & "'"
OldVal = ""
NewVal = ""
End Sub

我遇到的问题是,由于某种原因,它永远不会显示以前的值。它将仅在Sheet FA Cell B5从''更改为'12'时输出它,即使例如10表示在单元格中也是如此。

我也很想知道有没有办法让你可以随时使用这段代码。我更喜欢点击一个按钮,此时它会启动并开始记录更改。

由于

3 个答案:

答案 0 :(得分:2)

我发布了您发布的代码以进行一项非常小的更改:

Public OldVal As String
Public NewVal As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub
    OldVal = Target.Value
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim LDate As String
    If Target.Cells.Count > 1 Then Exit Sub
    NewVal = Target.Value
    Application.EnableEvents = False
        Sheets("corrections").Cells(Rows.Count, "A").End(xlUp)(2).Value = Now & "_Sheet " & ActiveSheet.Name & " Cell " & Target.Address(0, 0) & " was changed from '" & OldVal & "' to '" & NewVal & "'"
    Application.EnableEvents = True
    OldVal = ""
    NewVal = ""
End Sub

关于第二个问题,请从:

开始
Application.EnableEvents = False

将按钮挂在像这样的宏上:

Sub StartLogging()
    Application.EnableEvents = True
End Sub

答案 1 :(得分:0)

您的代码对我来说很好。至于启用/禁用宏,您只需要在每个IF(在两个宏中)之前(/上方)插入此行。可选择检查更合适的单元格来存储是/否选项(而不是" X1"):

If Sheets("corrections").Range("X1") <> "Yes" Then Exit Sub
' where you can change X1 for a more appropriate cell

要创建按钮,只需添加形状/对象并分配以下宏:

Sub Enable_Logs()
Sheets("corrections").Range("X1").Value = "Yes"
End Sub
Sub Disable_Logs()
Sheets("corrections").Range("X1").Value = "No"
End Sub

注意!要添加分配了宏的按钮:按Alt + N,+ SH并选择形状。然后,右键单击形状&gt;分配宏(并选择相应的宏)。 注意!第一次运行宏时,应手动设置&#34;是&#34;单元格X1中的值。

答案 2 :(得分:0)

为什么我的OldVal没有出现的问题是它被保存在阵列中。因此,当我告诉它看OldVal(1,1)时,它的工作原理应该如此。谢谢您的帮助。最终的工作代码是:

Public OldVal As String Public NewVal As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)     如果表格(“校正”)。范围(“G1”)&lt;&gt; “是”然后退出Sub         OldVal = Target.Value2

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)     如果表格(“校正”)。范围(“G1”)&lt;&gt; “是”然后退出Sub     如果Target.Cells.CountLarge&gt; 1然后退出Sub     NewVal = Target.Value         表格(“更正”)。单元格(Rows.Count,“A”)。结束(xlUp)(2).Value = Now&amp; “_Sheet”&amp; ActiveSheet.Name&amp; “细胞”&amp; Target.Address(0,0)&amp; “从''改变了'&amp; OldVal(1,1)&amp; “'到''&amp; NewVal&amp; “'”

OldVal = ""
NewVal = ""

End Sub