Excel VBA Static Timestamp in Worksheet_Change event

后端 未结 2 404
醉梦人生
醉梦人生 2020-12-07 04:11

I am working on creating a log that will automatically populate a timestamp into Cell D, when data is initially entered into Cell C. Unfortunately I have hit a wall.

<
相关标签:
2条回答
  • 2020-12-07 04:34

    Seems simple enough. Am I missing something? Just check to ensure the cell is blank before you update it.

    With rCell.Offset(0, 1)
        If .Value <> "" Then
            .Value = Now
            .NumberFormat = "hh:mm:ss AM/PM mm/dd/yyyy"
        End If
    End With
    
    0 讨论(0)
  • 2020-12-07 04:36

    The following puts a timestamp into column D if there isn't one there when a value is typed into column C. If the value in column C is cleared, any existing timestamp in column D is also cleared. If an edit is made to an entry in column C, then no change is made to the existing timestamp.

    Option Explicit
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Not Intersect(Target, Columns("C"), Target.Parent.UsedRange) Is Nothing Then
            On Error GoTo Safe_Exit
            Application.EnableEvents = False
            Dim rng As Range
            For Each rng In Intersect(Target, Columns("C"), Target.Parent.UsedRange)
                If CBool(Len(rng.Value2)) And Not CBool(Len(rng.Offset(0, 1).Value2)) Then
                    rng.Offset(0, 1) = Now
                ElseIf Not CBool(Len(rng.Value2)) And CBool(Len(rng.Offset(0, 1).Value2)) Then
                    rng.Offset(0, 1) = vbNullString
                End If
            Next rng
        End If
    Safe_Exit:
        Application.EnableEvents = True
    End Sub
    

    This routine will handle multiple cells as Target; typically when several rows of data is pasted into column C. It further restricts Intersection to the worksheet's UsedRange property so that processing is minimized when actions like row deletion are performed.

    0 讨论(0)
提交回复
热议问题