當(dāng)我們?cè)贓xcel中輸入或更新數(shù)據(jù)時(shí),有時(shí)需要自動(dòng)添加一個(gè)時(shí)間戳,表示當(dāng)前數(shù)據(jù)的最新更新時(shí)間。如下圖所示,當(dāng)在C列更新數(shù)據(jù)時(shí),在D列自動(dòng)加入更新時(shí)的時(shí)間。
可以用VBA代碼來實(shí)現(xiàn),實(shí)現(xiàn)步驟如下:
按Alt+F11,打開VBA編輯器。在“工程”窗口中雙擊“ThisWorkBook”,在右側(cè)的代碼窗口中粘貼下列代碼:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If ActiveSheet.Name <> "Sheet1" Then Exit Sub
If Target.Column = 3 Then Target.Offset(0, 1) = Now
End Sub
這樣,當(dāng)“Sheet1”表C列單元格中的內(nèi)容發(fā)生改變時(shí),Excel會(huì)自動(dòng)在D列同一行中的單元格中添加時(shí)間。
如果要將目標(biāo)區(qū)域指定為C2:C20,可以用下面的代碼:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If ActiveSheet.Name <> "Sheet1" Then Exit Sub
With Target
If .Column = 3 And .Row > 1 And .Row < 21 Then .Offset(0, 1) = Now
End With
End Sub
需要注意的是,當(dāng)目標(biāo)區(qū)域中的任意單元格內(nèi)容發(fā)生改變,包括刪除或更新數(shù)據(jù)時(shí),都將觸發(fā)Worksheet.SelectionChange 事件