VBA Excel - 在新行中插入

时间:2014-07-02 13:13:30

标签: excel vba

我的代码可以将用户名和时间戳插入电子表格。但是,它目前会覆盖现有记录。我正在努力为代码添加逻辑,所以当打开电子表格时,新的用户名/时间戳会附加到下一个空白行。非常感谢任何帮助!

Private iNextRow As Long
Const HIDDEN_SHEET As String = "Sheet3"

Private Sub Workbook_Open()
With Worksheets(HIDDEN_SHEET)
.Range("A1").Value = Environ("UserName")
.Range("B1").Value = Format(Date + Time, "dd mmm yyyy hh:mm:ss")
End With
iNextRow = 2

End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
On Error GoTo wb_exit
Application.EnableEvents = False
If Sh.Name <> HIDDEN_SHEET Then
With Worksheets(HIDDEN_SHEET)
.Range("A" & iNextRow).Value = Environ("UserName")
.Range("B" & iNextRow).Value = Format(Date + Time, "dd mmm yyyyhh: mm: ss ")
End With
End If

wb_exit:
Application.EnableEvents = True
End Sub

3 个答案:

答案 0 :(得分:0)

找到要放置新数据的范围 range.EntireRow.Insert range = range.Offset(-1, 0) 然后填写数据

答案 1 :(得分:0)

试试这个:

 Dim nextRow as integer

 nextRow = Range("A1").End(xlDown).Offset(1,0).Row
 Cells(nextRow,1)=(Environ$("Username"))
 Cells(nextRow,2)=VBA.Now()

答案 2 :(得分:0)

无法避免重写asp8811的优秀解决方案:

With Sheet3.Range("A1").End(xlDown)
    .Offset(1,0) = environ$("UserName")
    .Offset(1,1) = Now
End with