Solved

Access 2010: Use ID of inserted record in VBA code

Posted on 2014-04-07
11
3,535 Views
Last Modified: 2014-04-09
I have created the following insert statement and it is working.

    strQuery = "INSERT INTO tblDocuments(DocumentControlNumber, ExistingControlNumber, DocumentName, FileName, CreateDate, DepartmentID, AuthorID, OwnerID, EPD, Casters, Hinges, Other, ProcedureObjective, IsProcess, IsWorkInstruction, IsForm, IsMisc, DocStatus, RevisionDate, Revision) " & _
                "SELECT tblDocuments.DocumentControlNumber, tblDocuments.ExistingControlNumber, tblDocuments.DocumentName, tblDocuments.FileName, " & _
                "tblDocuments.CreateDate, tblDocuments.DepartmentID, tblDocuments.AuthorID, tblDocuments.OwnerID, tblDocuments.EPD, tblDocuments.Casters, tblDocuments.Hinges, tblDocuments.Other, " & _
                "tblDocuments.ProcedureObjective, tblDocuments.IsProcess, tblDocuments.IsWorkInstruction, tblDocuments.IsForm, tblDocuments.IsMisc, tblDocuments.DocStatus, Date() AS RevisionDate, '00' & Val([tblDocuments.Revision])+1 AS Revision " & _
                "FROM tblDocuments " & _
                "WHERE (((tblDocuments.DocumentID)=" & Me.SearchResults.Column(0) & "));"
   
    MsgBox (strQuery)
    dbData.Execute strQuery

I would like to use the ID from this record in additional queries after this.  How do I assign the ID for the last record inserted to a value which can be used?
0
Comment
Question by:btgtech
  • 4
  • 4
  • 2
  • +1
11 Comments
 

Expert Comment

by:kevinrea
ID: 39984848
why don't you just have a hidden text field and when you create that last record, it also copies the index number to the hidden text field.
then, you can just get the value of that hidden text field and use it as you need to.

kevin rea
Lancaster, Calif.
0
 

Author Comment

by:btgtech
ID: 39984859
This code is developed for a button on the form.  I am writing code to
1. Copy a record to a new version of the record
2. Using the ID from the new record,
     - Copy the records from a sub table (s) to a new version of the record in the sub table(s)

I was not planning on going back to the form.

What code would you use to identify the last record?
0
 

Expert Comment

by:kevinrea
ID: 39984864
just add a new field to a table, and then have that field in the form you use to create the new record.
then just refer to the table and that field to use in the future.

kevin rea
0
 

Author Comment

by:btgtech
ID: 39984882
There is already an autonumbered field in the table.  I just want to know how to query and assigned the autonumbered value to a value that I can use.
0
 
LVL 3

Accepted Solution

by:
Oliver Wastell earned 500 total points
ID: 39985403
You might want to rethink the way you have implemented this.  When I am looking to obtain the id of a new record I work with recordsets, for example:

    Dim db As DAO.Database
    Dim rsCustomisationRate As DAO.Recordset
    Dim sqlCustomisationRate As String
    Dim lngID As Long

    sqlCustomisationRate = "SELECT tblCustomisationRate.idCustomisationRate, " & _
			 "tblCustomisationRate.fkWorkshop , " & _
			 "tblCustomisationRate.fkCustomisationType, " & _
			 "tblCustomisationRate.customisationRate , " & _
			 "FROM tblCustomisationRate " & _
			 "WHERE tblCustomisationRate.idCustomisationRate=0"

    Set db = CurrentDb()
    Set rsCustomisationRate= db.OpenRecordset(sqlCustomisationRate dbOpenDynaset)
    With rsCustomisationRate
        .AddNew
            !fkWorkshop = Me!cmbFkWorkshop
            !fkCustomisationType = Me!cmbFkCustomisationType
            !customisationRate = Me!txbCustomisationRate
            lngID = !idCustomisationRate
        .Update
        .Close
    End With
    Set rsCustomisationRate = Nothing
    Set db = Nothing

Open in new window


The id of the new record is then stored here in lngID.  Obviously this is a snippet of code taken from one of my existing projects but hopefully you can see how you could tailor it for your own purposes.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 34

Expert Comment

by:PatHartman
ID: 39986663
I agree with Oliver.  Using a recordset is the best solution.  However, if your tables are SQL Server or some other RDBMS, you need to change the technique a little since unlike with Jet/ACE, the autonumber (identity) column isn't available until AFTER the rs.Update.  For SQL Server, et al, you will need to use the @Identity method to retrieve the new identity column value.  See http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/ for details
0
 

Author Comment

by:btgtech
ID: 39987479
If I have a field that I would like to assign today's date to - what function can be used in access to do this?
0
 

Author Comment

by:btgtech
ID: 39987743
I have the DAO process working.

Now I would like to use the DocumentID to query and update 8 other tables.  The other tables may have multiple records related to the documentID in then and now we need to have the same records assigned to the new DocumentID.

Thoughts?
0
 
LVL 3

Expert Comment

by:Oliver Wastell
ID: 39987841
For the date simply use Date(), or for current date / time use now().
0
 
LVL 3

Expert Comment

by:Oliver Wastell
ID: 39987849
If you need to make changes to existing records you'll probably want an UPDATE query and to add new ones you'll need an APPEND query. Design your queries in the query builder then cut and paste the sql into a VBA procedure. Then alter the sql string to pull in the new documentID in the appropriate place(s). You can then execute the sql strings using the method in your first post.

Happy to provide additional information if required but perhaps this should be done under a new question (post the link for the new question here) as your original issue I think has been resolved?
0
 
LVL 3

Expert Comment

by:Oliver Wastell
ID: 39988410
btgtech:
Thanks for the points and grading.  If you do post an additional question I'll take a look upon reaching my holiday destination in the next 48 hours if no one else has answered it in the meantime - just leaving the office now.  Thanks again.
0

Featured Post

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

Suggested Solutions

In the previous article, Using a Critera Form to Filter Records (http://www.experts-exchange.com/A_6069.html), the form was basically a data container storing user input, which queries and other database objects could read. The form had to remain op…
Experts-Exchange is a great place to come for help with solutions for your database issues, and many problems are resolved within minutes of being posted.  Others take a little more time and effort and often providing a sample database is very helpf…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

760 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

19 Experts available now in Live!

Get 1:1 Help Now