Solved

How to get key of new row after adding?

Posted on 2013-01-12
12
336 Views
Last Modified: 2013-01-12
Hello - when you add a record to an Access (2010) table in VBA, using .AddNew, .Update, and the primary key is an AutoNumber field, is there a dependable way to get that new primary key value?

I am currently using DMax(), but I want to be completely sure I'm getting the record *I* just added, and not that of somebody that slipped in right after my update.

Thanks
0
Comment
Question by:mlagrange
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 61

Accepted Solution

by:
mbizup earned 250 total points
Comment Utility
If you are recording usernames in your records, add the submitters user id to your DMax criteria.
0
 
LVL 22

Assisted Solution

by:Kelvin Sparks
Kelvin Sparks earned 250 total points
Comment Utility
Strraight after the .Update you can set a variable that is equal to !PKfieldname. If you do this before you move off the record or close the recordset, you will have the PK of the record you created.

i.e. varPK = rs!PKFieldname


Kelvin
0
 
LVL 61

Expert Comment

by:mbizup
Comment Utility
Ah... right.   If you are using recordset code,  kelvin's suggestion is hands down the best way to do this.
0
 

Author Comment

by:mlagrange
Comment Utility
Kevin - I like that, but I'm getting "no current record" when it hits that line.
Do I have to back up to the previous record or something?
Here's the code (this "NoMatch" is right after a ".Seek"; if NoMatch. I have to add a record, and then add a child record to the newly-added record, so I need this newly-added record key):

If rstAHdrs.NoMatch Then
        With rstAHdrs
            .AddNew
            ...setting field values...
            .Update
            lngAHdrID = ![AllocHdrID]   '-- trying to save off; "AllocHdrID" is the primary key
        End With
    Else
        '-- record exists; get the pkey
        lngAHdrID = rstAHdrs![AllocHdrID]
    End If
0
 

Author Comment

by:mlagrange
Comment Utility
*Kelvin*  
Sorry...
0
 

Author Comment

by:mlagrange
Comment Utility
Ok, I added a .MoveLast. That should be "timely" enough?        

        With rstAHdrs
            .AddNew
            ...setting field values...
            .Update
            *.MoveLast*
            lngAHdrID = ![AllocHdrID]
        End With
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Closing Comment

by:mlagrange
Comment Utility
Thanks to you both for your responses
0
 
LVL 75

Expert Comment

by:DatabaseMX (Joe Anderson - Access MVP)
Comment Utility
"That should be "timely" enough?"
No.

mx
0
 
LVL 61

Expert Comment

by:mbizup
Comment Utility
I  believe it has to be immediately before the update.
0
 
LVL 75

Expert Comment

by:DatabaseMX (Joe Anderson - Access MVP)
Comment Utility
No need for MoveLast ...
       
       With rstAHdrs
            .AddNew
            ...setting field values...
            .Update
            .Move 0, .LastModified          
            lngAHdrID = ![AllocHdrID]
        End With

However, if ... you really want to be sure you are getting the last ID you added ... the mbizup's approach with UserName in the first post is the closest.
0
 

Author Comment

by:mlagrange
Comment Utility
Ok, I'll use that one - Thanks
0
 
LVL 61

Expert Comment

by:mbizup
Comment Utility
Hang on there!  :-)

Did you see my comment at http:#a38770941, and Kelvin's explanation?

<<< If you do this before you move off the record or close the recordset, you will have the PK of the record you created.  >>>

The catch is it has to be while you are still editing your new record.  That means (and a minor correction to his post)  before the .Update statement.  If you do this, you are absolutely, positively guaranteed to get the ID of the record you are creating because the ID you are pulling is directly from the recordset (which no one else is using) and the record you are currently editing.  


Using a test table called Table1 and a field called txtField when adding a new record:

Function AddRecord()
    Dim rs As DAO.Recordset
    
    Set rs = CurrentDb.OpenRecordset("Table1", dbOpenDynaset)
    
    rs.AddNew
    rs!txtFld = "blah"
    AddRecord = rs!ID
    rs.Update
    
End Function

Open in new window


Call it with a messagebox to display the value of the ID added:

msgBox AddRecord

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Most if not all databases provide tools to filter data; even simple mail-merge programs might offer basic filtering capabilities. This is so important that, although Access has many built-in features to help the user in this task, developers often n…
It took me quite some time to sort out all the different properties of combo and list boxes available from Visual Basic at run-time. Not that the documentation is lacking: the help pages are quite thorough and well written. The problem was rather wh…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
In Microsoft Access, learn how to “cascade” or have the displayed data of one combo control depend upon what’s entered in another. Base the dependent combo on a query for its row source: Add a reference to the first combo on the form as criteria i…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now