这是一段代码,当行中的任何单元格发生变化时,它会在所选单元格中加盖时间戳。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range, c As Range
Const DateStampColumn As Long = 10 'Date stamp column number
For Each r In Target.Rows
For Each c In r.Cells
If Not IsEmpty(c) Then
Application.EnableEvents = False
Cells(r.Row, DateStampColumn).Value = Date
Application.EnableEvents = True
Exit For
End If
Next c, r
End Sub
是否可以修改此代码,使其仅适用于我在工作表上的表格范围。我的表名为table6,其固定列范围为A-P。但是,随着新数据的添加,行数将变得灵活。
答案 0 :(得分:2)
我刚刚将此代码添加到您之前的问题中。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range, r1 As Range
Const DateStampColumn As Long = 8 'Date stamp column number
Set r1 = Intersect(Target, activeSheet.ListObjects("Table6").DataBodyRange)
If Not r1 Is Nothing Then
For Each r In r1
If Not IsEmpty(r) Then
Application.EnableEvents = False
Cells(r.Row, DateStampColumn).Value = Date
Application.EnableEvents = True
'Exit For
End If
Next r
End If
End Sub
答案 1 :(得分:0)
这是一段代码,当行中的任何单元格发生变化时,它会在所选单元格中加盖时间戳。
然后你可以避免循环
Private Sub Worksheet_Change(ByVal Target As Range)
Const DateStampColumn As Long = 10 'Date stamp column number
Dim tblRng As Range
If WorksheetFunction.CountBlank(Target) = Target.Count Then Exit Sub ' do nothing if cells are being cleared
Set tblRng = Me.ListObjects("Table6").DataBodyRange
If Intersect(Target, tblRng) Is Nothing Then Exit Sub ' do nothing if changed cells do not belong to "Table6" table
Application.EnableEvents = False
Intersect(tblRng.Columns(DateStampColumn), Target.EntireRow) = Date
Application.EnableEvents = True
End Sub