1

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

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

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

我也很想知道是否有一种方法可以让你拥有它,这样这段代码就不会一直运行。我更喜欢单击一个按钮,然后它将启动并开始记录更改。

谢谢

4

3 回答 3

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
于 2013-10-04T13:35:59.943 回答
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 并选择一个形状。然后,右键单击形状 > 分配宏(并选择相应的宏)。笔记!第一次运行宏时,应在单元格 X1 中手动设置“是”值。

于 2013-10-04T13:48:54.010 回答
0

我的 OldVal 没有出现的问题是它被排列成数组。因此,当我告诉它查看 OldVal(1, 1) 时,它可以正常工作。谢谢您的帮助。最终的工作代码是:

公共 OldVal 作为字符串 公共 NewVal 作为字符串

Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Sheets("corrections").Range("G1") <> "Yes" Then Exit Sub OldVal = Target.Value2

结束子

Private Sub Worksheet_Change(ByVal Target As Range) If Sheets("corrections").Range("G1") <> "Yes" Then Exit Sub If Target.Cells.CountLarge > 1 Then Exit Sub NewVal = Target.Value Sheets("更正").Cells(Rows.Count, "A").End(xlUp)(2).Value = Now & "_Sheet " & ActiveSheet.Name & " Cell " & Target.Address(0, 0) & " 是从 '" & OldVal(1, 1) & "' 更改为 '" & NewVal & "'"

OldVal = ""
NewVal = ""

结束子

于 2013-10-09T17:59:58.477 回答