Solved

Access 2010: Use ID of inserted record in VBA code

Posted on 2014-04-07
11
3,693 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

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
 
LVL 38

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s been over a month into 2017, and there is already a sophisticated Gmail phishing email making it rounds. New techniques and tactics, have given hackers a way to authentically impersonate your contacts.How it Works The attack works by targeti…
Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
What’s inside an Access Desktop Database. Will look at the basic interface, Navigation Pane (Database Container), Tables, Queries, Forms, Report, Macro’s, and VBA code.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

691 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