同一个Excel工作表中的VBA 2时间戳

问题描述 投票:0回答:2

当我在列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
excel vba excel-vba
2个回答
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。将在任何活动的工作表上输入时间戳。考虑完全限定工作簿和工作表。


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
© www.soinside.com 2019 - 2024. All rights reserved.