Excel VBA - 单元格更改,列中的时间戳

时间:2012-09-13 08:08:19

标签: excel excel-vba vba

我想创建两个日期戳,一个用于OK,一个用于NOT OK。这些值填入A列,分别为'x' for OK'NOK' for NOT OK

当在列A中填入'x'时,第49列中的值应该是填写'x'时的日期戳。

当列中填写'NOK'时,第52列中的值应为填写'NOK'时的日期戳。

此外,如果从列A中删除“x”或“NOK”,则日期戳也会消失。这就是我所拥有的。

Private Sub Worksheet_Change(ByVal Target As Range)
    '49 = ok
    '52 = NOK

    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set LastRow = Range("A" & Rows.Count).End(xlUp).Row
    Set KeyCells = Range("A1:" & LastRow)

    If Application.Intersect(KeyCells, Range(Target.Address)) Like "*x*" Then
        Cells(Row, 49).Value = Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")
    End If

    If Application.Intersect(KeyCells, Range(Target.Address)) Like "*NOK*" Then
        Cells(Row, 52).Value = Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")
    End If

End Sub

1 个答案:

答案 0 :(得分:3)

在这里,试试这个:

Private Sub Worksheet_Change(ByVal Target As Range)
    '49 = ok '52 = NOK
    Application.EnableEvents = False

    With Target
    'check if change happend in column A
    If .Column = 1 Then
      'check if changed value is X
      If .Value Like "*x*" Then
          'add datestamp if it is
          Cells(.Row, 49).Value = Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")
      Else
          'clear datestamp if not
          Cells(.Row, 49).Value = ""
      End If

      If .Value Like "*NOK*" Then
          Cells(.Row, 52).Value = Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")
      Else
          Cells(.Row, 52).Value = ""
      End If
    End If
    End With
    Application.EnableEvents = True
End Sub