如何解决使用 VBA 在 Excel 中使用一次性时间戳
我正在尝试创建一个 Excel 日志,并且想要一个时间戳来捕获第一次插入或更改另一个字段中的信息的时间。我可以使用 VBA 并创建时间戳,但如果用户返回并更改目标单元格中的数据,时间戳也会更新。
出于我的测试目的,我在同一行的 B 列和 A 列中插入基本信息会生成一个正确的时间戳。如果我返回并更改 B 列中该行中的信息,时间戳会更新,这是我不想要的。
如何防止时间戳在插入后更新?
当前时间戳 VBA 代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xRInt As Integer
Dim xDStr As String
Dim xFStr As String
On Error Resume Next
xDStr = "B" 'Data Column
xFStr = "A" 'Timstamp Column
If (Not Application.Intersect(Me.Range(xDStr & ":" & xDStr),Target) Is Nothing) Then
xRInt = Target.Row
Me.Range(xFStr & xRInt) = Format(Now(),"mm/dd/yyyy hh:mm:ss")
End If
End Sub
解决方法
工作表更改 - 时间戳
- 当手动或通过
B
更改列VBA
的单元格中的值时,如果尚未更改,代码将向列A
的同一行中的单元格添加时间戳.
代码
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const tCol As String = "A"
Const cCol As String = "B"
Const tPattern As String = "mm/dd/yyyy hh:mm:ss"
Dim rg As Range: Set rg = Intersect(Columns(cCol),Target)
If rg Is Nothing Then Exit Sub
Dim tStamp As String: tStamp = Format(Now,tPattern)
Dim cOffset As Long: cOffset = Columns(tCol).Column - Columns(cCol).Column
Dim arg As Range
Dim cel As Range
Application.ScreenUpdating = False
For Each arg In rg.Areas
For Each cel In arg.Cells
With cel.Offset(,cOffset)
If Len(.Value) = 0 Then
.Value = tStamp
End If
End With
Next cel
Next arg
Application.ScreenUpdating = True
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。