我想使用注释来记录单元格中的每个更改,但每次执行代码时Excel都会崩溃。
对于Undo部分,有没有更好的方法来记录旧值和新值?
谁能给我一些建议?谢谢
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range
Dim ws As Worksheet
For Each r In Target
new_value = r.Value
Application.Undo
old_value = r.Value
r.Value = new_value
If r.Value = "" And r.Comment Is Nothing Then
r.AddComment.Text Application.UserName & " has added " & new_value & " at " & Now
ElseIf r.Value <> "" And r.Comment Is Nothing Then
r.AddComment.Text Application.UserName & " has changed from " & old_value & " to " & new_value & " at " & Now
ElseIf Not r.Value = "" And r.Comment Is Nothing Then
r.Comment.Text Application.UserName & " has changed from " & old_value & " to " & new_value & " at " & Now
End If
Next
End Sub
为了避免Excel运行到无限循环,您需要关闭事件
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range
Dim ws As Worksheet
Application.EnableEvents = False
For Each r In Target
new_value = r.Value
Application.Undo
old_value = r.Value
r.Value = new_value
If r.Value = "" And r.Comment Is Nothing Then
r.AddComment.Text Application.UserName & " has added " & new_value & " at " & Now
ElseIf r.Value <> "" And r.Comment Is Nothing Then
r.AddComment.Text Application.UserName & " has changed from " & old_value & " to " & new_value & " at " & Now
ElseIf Not r.Value = "" And r.Comment Is Nothing Then
r.Comment.Text Application.UserName & " has changed from " & old_value & " to " & new_value & " at " & Now
End If
Next
Application.EnableEvents = True
End Sub
现在,您可以检查您的代码是否正在执行您希望它执行的操作。