Excel VBA – 单元格更改,date戳记列

我想创build两个date戳,一个是确定的,一个是不正确的。 这些值填写在A列中, 'x' for OK 'NOK' for NOT OK

当列A中填入“x”时,列49中的值应该是填入“x”时的date戳。

当在列中填写“NOK”时,列52中的值应该是填写“NOK”时的date戳。

此外,如果从列A中删除“x”或“NOK”,那么date戳也应该消失。 这是我的。

 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 

在这里,试试这个:

 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