我的Sheet1看起来像这样
运行此代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim WorkRng As Range
Dim rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.ActiveSheet.Range("B2:K10"), Target)
xOffsetColumn = 11
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each rng In WorkRng
If Not VBA.IsEmpty(rng.Value) Then
rng.Offset(0, xOffsetColumn).Value = Now
rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
Else
rng.Offset(0, xOffsetColumn).ClearContents
End If
Next
Application.EnableEvents = True
End If
End Sub
到目前为止,它是做什么的
B2:K10
范围内的任何内容时,它会将日期和时间添加到表格的右侧我需要什么:
Sheet2
开始将日期和时间以及相应的步骤和项目记录到A2
预期结果:
并不断在最后一行下面添加内容,如果从Sheet1
的单元格中删除了值,则永远不要擦除记录。如果需要,将手动删除记录。
答案 0 :(得分:0)
尝试
Private Sub Worksheet_Change(ByVal Target As Range)
Dim WorkRng As Range
Dim rng As Range
Dim nextRow As Long
Set WorkRng = Intersect(Application.ActiveSheet.Range("B2:K10"), Target)
If Not WorkRng Is Nothing Then
Application.EnableEvents = False
For Each rng In WorkRng
If Not VBA.IsEmpty(rng.Value) Then
nextRow = Log.Cells(Rows.Count, 1).End(xlUp).Row + 1
Log.Cells(nextRow, 1) = Me.Cells(rng.Row, 1)
Log.Cells(nextRow, 2) = Me.Cells(1, rng.Column)
Log.Cells(nextRow, 3) = Now
Log.Cells(nextRow, 3).NumberFormat = "dd-mm-yyyy, hh:mm:ss"
End If
Next
Application.EnableEvents = True
End If
End Sub
代码标识工作表2中下一个空行的行号,然后将值写入该行的前三个单元格中。
编辑:在看到对代码的编辑之后:您无需费心声明一个工作表变量,然后将其设置为工作表。而是使用(Name)
属性为工作表命名,然后您可以通过该名称从代码中的任何位置访问它。我调整了代码以反映这一点。