Access: Get newly created auto number in DAO

家住魔仙堡 提交于 2019-12-10 17:10:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!