简体   繁体   中英

VBA Excel - Insert in New Row

I have code that works to insert a username and timestamp into a spreadsheet. However, it currently overwrites the existing records. I'm struggling with adding logic to the code so when the spreadsheet is opened, the new username/timestamp is appended to the next blank row. Any assistance is greatly appreciated!

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

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

Try this:

 Dim nextRow as integer

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

Could not refrain to re-write slightly asp8811 excellent solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM