工作表中有一个表格。我想使用VBA捕获对该表所做的任何更改。这可能吗?
例如,C4 = 14
开头。如果用户更改为C4 = 18
,我想知道哪个单元格已更改(在这种情况下为C4
)以及更改为哪个(在这种情况下为18
)。
对于高级功能,如果用户添加了一行,则将C4
更改为C5
(在第4行上方添加一行),然后添加C4 = 11
(新C4
)。可以抓住这个吗?删除原始行4怎么样?是否可以捕获已删除的内容?
感谢任何帮助。
由于
答案 0 :(得分:0)
Unfortunately the answer's no, not really. By the time the worksheet change event is triggered, the target's value is the new value and the old value is lost.
I did once read of someone maintaining a hidden workbook that kind of mirrored every action that was done to the target workbook and could hence be used to track the changes. But obviously this is a lot of effort.
An alternative might be to try something using Application.Undo. So, from the worksheet change event, record what the value is, apply Application.Undo, record that value, then replace with the first value. It's really messy though.
答案 1 :(得分:0)
假设我们的表格 A1 至 D4 。在工作表代码区域中输入以下代码:
Public OldValue As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Range("A1:D4"), Target) Is Nothing Then
Else
If Target.Count = 1 Then
MsgBox "Previous Value: " & OldValue & vbCrLf & "New value: " & Target.Value
End If
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Intersect(Range("A1:D4"), Target) Is Nothing Then
Else
If Target.Count = 1 Then
OldValue = Target.Value
End If
End If
End Sub
这适用于简单的单细胞点击和类型编辑。 SelectionChange
检测并记录旧值。 Change
显示旧值和新值。
这对多单元格复制/粘贴无效。