VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Returning the Autonumber Value when adding records

by James N. Wink (2 Submissions)
Category: Databases/Data Access/DAO/ADO
Compatability: Visual Basic 3.0
Difficulty: Beginner
Date Added: Wed 3rd February 2021
Rating: (7 Votes)

When using Autonumber fields in a database for a UID, you might need this value after you add the record, for that record. This is my example of how to get that value back from the database after it is added using DAO or ADO.

Assumes
This is not a complete application, just code snippets. I expect that anyone using this knows that they have to set references to DAO and ADO, and know how to connect to a database using these objects.
Side Effects
none.

Rate Returning the Autonumber Value when adding records

'DAO Example  
'First Open a updateable recordset
Set rs = db.OpenRecordset("SomeTable")
  With rs
    'Start a New Record
    .AddNew
      !Field2 = "Add your data for this new record" 
    'Add the record to the database
    .Update
  
    'Set the bookmark to Last modified
    .Bookmark = .LastModified
    
    lngResult = rs!AutoNumberUID
  End With
  
  rs.Close
'Ado Example
  Set mrsMDB = New ADODB.Recordset
  
  mrsMDB.CursorType = adOpenKeyset
  mrsMDB.LockType = adLockOptimistic
  mrsMDB.Open "SomeTable", mcnnMDB, , , adCmdTable
      
  With mrsMDB
    .AddNew
    !Field2 = "Add your Data for this record"
    .Update
    varBkMark = .Bookmark
    .Requery
    .Bookmark = varBkMark
    lngNewUID = !AutoNumberUID
    
  End With

Download this snippet    Add to My Saved Code

Returning the Autonumber Value when adding records Comments

No comments have been posted about Returning the Autonumber Value when adding records. Why not be the first to post a comment about Returning the Autonumber Value when adding records.

Post your comment

Subject:
Message:
0/1000 characters