gpt4 book ai didi

excel - VBA - 删除数据和过滤器更改时触发的自动时间戳

转载 作者:行者123 更新时间:2023-12-04 20:52:17 25 4
gpt4 key购买 nike

我只是想在excel上添加一个自动时间戳。

您能否就我在使用表格进行批量插入/删除时遇到的 2 个问题提供建议

1,在多行删除时,时间戳仍然存在,希望将其删除

2,在多行插入/删除时时间戳会出错提前感谢

提前致谢

Private Sub Worksheet_Change(ByVal Target As Range)

Dim myTableRange As Range, TargetVal As String
Set myTableRange = Range("C2:Y1048576") 'Change to your range..
If Intersect(Target, myTableRange) Is Nothing Then Exit Sub

With Application
.ScreenUpdating = False
.EnableEvents = False
.Undo
TargetVal = Target.Value
.Undo
If Target.Value <> TargetVal Then

'Your Code doing something with timestamp
Set myDateTimeRange = Range("A" & Target.Row)

'Column for last updated date/time
Set myUpdatedRange = Range("B" & Target.Row)

'Set Time Stamp Value
myDateTimeRange.Value = Format(Now)

'Column for last updated date/time
myUpdatedRange.Value = Format(Now)

Debug.Print Target.Value
End If
.EnableEvents = True
.ScreenUpdating = True
End With

End Sub

最佳答案

那这个呢:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim myTableRange As Range, IntSectRange As Range, TargetVal As String
Set myTableRange = Range("A2:B" & Cells(Rows.Count, 2).End(xlUp).Row) 'Change to your range..
Set IntSectRange = Intersect(Target, myTableRange)
If IntSectRange Is Nothing Then
Exit Sub
Else
If IntSectRange.Cells.Count = 1 Then 'Thus when only one cell gets changed
With Application
.ScreenUpdating = False
.EnableEvents = False
.Undo
TargetVal = Target.Value
.Undo
If Target.Value <> TargetVal Then
'Your Code doing something with timestamp
Debug.Print Target.Value
End If
.EnableEvents = True
.ScreenUpdating = True
End With
Else 'Thus when there are more cells involved (bulk)
'Your Code doing something with timestamp
End If
End If

End Sub

代码将首先检查范围是否相交,如果是,则撤消上一个用户操作,检查其值,重做用户的操作并验证是否输入了新值或删除了值。

您可能希望为行添加另一个测试(动态 myTableRange),以防用户一次删除整行,这会出错。

关于excel - VBA - 删除数据和过滤器更改时触发的自动时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com