问题
I have a code in DAO that connects to a linked table in SQL Server 2008. I need to get the newly created auto number on .AddNew
.
Set db = CurrentDb
Set rs = db.OpenRecordset("AuditTrail")
rs.AddNew
rs("ActionID") = actionAdd
rs("dtDateTime") = Now()
rs("FormName") = frmName
rs("TableName") = tblName
rs("RecordID") = actionAdd
rs("Comment") = Nz(comment, "")
rs("UserID") = UserIDName
rs("UsernamePC") = VBA.Environ("USERDOMAIN")
rs("DomainPC") = VBA.Environ("USERDOMAIN")
rs("ComputerNamePC") = VBA.Environ("COMPUTERNAME")
rs.Update
rs.Close
If I use rs("AuditTrailID")
before rs.Close
, it returns 1 (the first entry).
回答1:
Set the Bookmark
property equal to the LastModified
property to go back to the record you just added.
Edit: As Conrad Frix noted, use the dbSeeChanges
option when opening the recordset:
Set db = CurrentDb
Set rs = db.OpenRecordset(Name:="AuditTrail", Options:=dbSeeChanges)
rs.AddNew
rs("ActionID") = actionAdd
' ... update additional fields
rs.Update
rs.Bookmark = rs.LastModified
Debug.Print rs("ID")
rs.Close
回答2:
If it is a SQL Server database you are inserting into, would not a trigger on the database be a better solution.
来源:https://stackoverflow.com/questions/8839377/access-get-newly-created-auto-number-in-dao