我想做的是,当我在列中插入某些内容A
或B
将当前日期和时间插入/更新到列中时D
。当然我已经这样做了,但我想排除列C
,D
这意味着当在这些列中插入某些内容时,不应插入/更新日期/时间。
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row > 1 Then Cells(Target.Row, "D") = Now()
End Sub
另外我还有另一个代码,但仍然找不到排除某些列的方法(以使更新日期/时间的列范围有效)
Private Sub Worksheet_Change(ByVal Target As Range)
If Target(1, 1).Row > 1 Then
With Cells(Target(1, 1).Row, "D")
.Value = Now
.NumberFormat = "dd-mm-yyyy, hh:mm:ss"
End With
End If
End Sub
编辑:这是我的最终代码。
Private Sub Worksheet_Change(ByVal Target As Range)
If (Target.Row > 1) And (Target.Column = 1) Then
With Cells(Target.Row, "D")
.Value = Date
.NumberFormat = "dd-mm-yyyy"
End With
End If
If (Target.Row > 1) And (Target.Column = 2) Then
With Cells(Target.Row, "E")
.Value = Now
.NumberFormat = "dd-mm-yyyy, hh:mm:ss"
End With
End If
End Sub
答案1
除了行条件之外,还添加需要满足 A 列和 B 列的条件:
Private Sub Worksheet_Change(ByVal Target As Range)
If (Target.Row > 1) And ((Target.Column = 1) Or (Target.Column = 2)) Then
'Cells(Target.Row, "D") = Now()
With Cells(Target.Row, "D")
.Value = Now
.NumberFormat = "dd-mm-yyyy, hh:mm:ss"
End With
End If
End Sub
现在仅当编辑这两列时才会插入日期。
答案2
您必须检查:
- 该行不是 1
- 列为 1 或 2
- 目标是单细胞
有可能
- 当前行的 D 列为空
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row > 1 _
And Target.Column <= 2 _
And Target.Cells.Count = 1 Then
Cells(Target.Row, "D") = Now()
End If
End Sub
复制粘贴包含超过 1 个单元格的范围时,此代码将不起作用。
答案3
尝试一下:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Long
r = Target.Row
c = Target.Column
If r > 1 And (c = 1 Or c = 2) Then
If Cells(r, "C") = "" And Cells(r, "D") = "" Then
Application.EnableEvents = False
Cells(r, "D") = Now()
Application.EnableEvents = True
End If
End If
End Sub
这应该测试所有必需的条件。