Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access: Get newly created auto number in DAO

Tags:

vba

dao

ms-access

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).

like image 755
Rick Avatar asked Jan 12 '12 17:01

Rick


1 Answers

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
like image 158
Rachel Hettinger Avatar answered Oct 04 '22 03:10

Rachel Hettinger