当我在列A中输入文本时,我试图在列B中获取时间戳,当我在列C中输入文本时,我想在列D中单独设置时间戳。
我发现这个VBA代码可以完美地用于1个时间戳,但我需要帮助才能使它在同一个工作表中有2个独立的时间戳。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
xCellColumn = 1
xTimeColumn = 2
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
If xCol = xCellColumn Then
Cells(xRow, xTimeColumn) = Now()
End If
End If
End Sub
答案 0 :(得分:0)
Offset
属性是你的朋友:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Text <> "" Then
'Check if column A or C was updated
If Target.Column = 1 Or Target.Column = 3 Then
'Disable events to stop recursive calls
Application.EnableEvents = False
'Place the date one column to the right
Target.Offset(, 1).Value = Now()
'Re-enable events
Application.EnableEvents = False
End If
End If
End Sub
答案 1 :(得分:0)
这样做你想要的吗?
Private Sub Worksheet_Change(ByVal Target As Range)
Application.enableevents = false
If Target.Text <> "" Then
Select case Target.Column
Case 1, 3 ' columns A and C for now, add more as needed.'
Cells(target.row, target.column + 1) = Now() ' +1 as column with timestamp always seems to be 1 column to the right of the newly entered value'
End select
End If
Application.enableevents = true
End Sub
上面的代码隐含地引用ActiveSheet。将在任何活动的工作表上输入时间戳。考虑完全限定工作簿和工作表。