Results 1 to 4 of 4
  1. #1
    Join Date
    May 2003
    Posts
    6

    Arrow Unanswered: Return an auto number key in Access

    in MS Access97, is there a way to return a key?

    For example,

    I have a field called contactID (auto number). Each time I create a new contact, I want a query to return that contactID I've just created so I can reference it somewhere else.

    Can you do that in Access? Thanks much!

  2. #2
    Join Date
    Jul 2003
    Location
    Michigan
    Posts
    1,941
    Here's one way to do it...

    Function GetContactId() as Long
    dim rs as DAO.Recordset
    Dim strSql as string
    strSql = "Select Max(ContactID) from Contacts"
    set rs = currentdb.openrecordset(strsql)
    GetContactID = rs!contactid
    rs.close
    set rs = nothing
    Exit Function

    Just call this function anytime you need the last contact id

    i.e.: lngContactID = GetContactID


    Mark
    Inspiration Through Fermentation

  3. #3
    Join Date
    May 2003
    Posts
    6
    if two people create a record at the same time, wouldn't this be a problem?

    for example,

    contact1 created a record
    contact2 created a record, simultaneously
    return contactid

    there's a problem here...

  4. #4
    Join Date
    Jul 2003
    Location
    Michigan
    Posts
    1,941
    OK, that's a little different.
    I'm guessing you're adding the contact from a form (or different forms).

    So change the code I posted before to:

    Function GetContactId(strContactName) as Long
    dim rs as DAO.Recordset
    Dim strSql as string
    strSql = "Select ContactID from Contacts where contact_name = '" & strContactName & "'"
    set rs = currentdb.openrecordset(strsql)
    GetContactID = rs!contactid
    rs.close
    set rs = nothing
    Exit Function

    You should be able to supply the contact name from the form that it has just been added to.
    Inspiration Through Fermentation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •