Home » excel » excel – If cell is updated, write cell value and timestamp in next blank row

excel – If cell is updated, write cell value and timestamp in next blank row

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to update a column with timestamp and another column with updates (which got from a specific cell).

Desired behaviour:
A2 has xy written to it. That change triggers a macro, which puts timestamp in C column at row 2 and the update in D column row 2.
If new update is made in A2: If C2 is not empty, jump to C3 and put timestamp and put update on D3 and so on.

Unfortunately, it puts the first update timestamp and the update to the columns, but if I update again, it doesn’t jump and put update there.

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
How to&Answers:

Please try this:

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