我想做的是,當我將某些內容插入 columnA
或B
將當前日期和時間插入/更新到 column 時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
這應該測試所有必需的條件。