2013-07-17 59 views
1

下面的代碼在輸入列A時檢測到數據,並自動將當前用戶插入到右側單元格中。我也想這個代碼添加一個時間戳。我需要記錄用戶名和時間。有什麼建議麼?Excel VBA時間戳和用戶名

Private Sub Worksheet_Change(ByVal Target As Excel.Range) 
    Dim rCell As Range 
    Dim rChange As Range 

    On Error GoTo ErrHandler 
    Set rChange = Intersect(Target, Range("A:A")) 
    If Not rChange Is Nothing Then 
     Application.EnableEvents = False 
     For Each rCell In rChange 
      If rCell > "" Then 
       With rCell.Offset(0, 1) 
        .Value = UserName() 

       End With 

      Else 
       rCell.Offset(0, 1).Clear 
      End If 
     Next 
    End If 

ExitHandler: 
    Set rCell = Nothing 
    Set rChange = Nothing 
    Application.EnableEvents = True 
    Exit Sub 
ErrHandler: 
    MsgBox Err.Description 
    Resume ExitHandler 
End Sub 

Public Function UserName() 
    UserName = Environ$("UserName") 
End Function 

回答

1

您可以使用像date & " " & time這樣的東西。這將輸出的日期和時間連接在一起,像這樣:

17/07/2013 11:49:39 PM 

這裏是你的代碼加入到下一列的日期/時間值:

Private Sub Worksheet_Change(ByVal Target As Excel.Range) Dim rCell As Range Dim rChange As Range 

On Error GoTo ErrHandler 
Set rChange = Intersect(Target, Range("A:A")) 
If Not rChange Is Nothing Then 
    Application.EnableEvents = False 
    For Each rCell In rChange 
     If rCell > "" Then 
      rCell.Offset(0, 1).Value = UserName() 
      rCell.Offset(0, 2).Value = date() & " " & time() <-- added line   
     Else 
      rCell.Offset(0, 1).Clear 
     End If 
    Next 
End If 
+0

太謝謝你了!完美的作品! – user2591771

+0

快樂的日子!請標記爲答案,以便問題關閉:-) – Katstevens

+0

'rCell.Offset(0,2).Value = Now()'也適用。 –