如果单元格已更新,则在下一个空白行中写入单元格值和时间戳

时间:2019-01-25 22:09:37

标签: excel vba

我试图用时间戳更新一列,并用更新(从特定单元格获得)更新另一列。

期望的行为:
A2上已写入xy。该更改将触发一个宏,该宏将时间戳记放置在第2行的C列中,并将更新放置在第2行的D列中。 如果在A2中进行了新的更新:如果C2不为空,则跳至C3并放置时间戳,然后在D3上进行更新,依此类推。

不幸的是,它会将第一个更新时间戳记和更新放在列中,但是如果我再次更新,它不会跳转并将更新放在那里。

Error message and Excel macro
Excel sheet which I try to update.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCellColumn As Integer
    Dim xCellRow As Integer
    Dim xTimeColumn As Integer
    Dim xTimeRow As Integer
    Dim xUpdateColumn As Integer
    Dim xUpdateRow As Integer
    Dim xRow, xCol As Integer
    xCellColumn = 2
    xCellRow = 10
    xTimeColumn = 6
    xTimeRow = 2
    xUpdateColumn = 7
    xUpdateRow = 2
    i = 2
    xCol = Target.Column
    xRow = Target.Row
    If Target.Text <> "" Then
       If xCol = xCellColumn Then
            If xRow = xCellRow Then
                Do While Range("Munka1").Cells(i, xTimeColumn).Value <> ""
                  i = i + 1
                Loop
                Cells(i, xTimeColumn) = Now()
                Cells(i, xUpdateColumn) = Target.Value
            End If
        End If
    End If
End Sub

1 个答案:

答案 0 :(得分:2)

请尝试以下操作:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCellColumn As Long
    Dim xCellRow As Long
    Dim xTimeColumn As Long
    Dim xUpdateColumn As Long
    Dim SupervisedArea As Range
    Dim i As Integer

    xCellColumn = 2
    xCellRow = 10
    xTimeColumn = 6
    xUpdateColumn = 7

    If Target.Text <> "" Then
        ' If any changed value in the whole column should generate a new data pair:
        'Set SupervisedArea = Intersect(Target, Me.Columns(xCellColumn))
        ' If only one cell should be supervised:
        Set SupervisedArea = Intersect(Target, Me.Cells(xCellRow, xCellColumn))
        If Not SupervisedArea Is Nothing Then
            i = 2
            Do While Me.Cells(i, xTimeColumn).Value <> ""
              i = i + 1
            Loop
            Application.EnableEvents = False
            Me.Cells(i, xTimeColumn) = Now()
            Me.Cells(i, xUpdateColumn) = Target.Value
            Application.EnableEvents = True
        End If
    End If
End Sub