Search code examples
ms-accessvbadao

How to retrieve the auto increment field name from a table?


I'm writing a function that gets the name of the AutoIncrement field in any given table

public sub GetID(ByVal tblName As String) As String
    Dim rs as RecordSet
    Dim fld as field

    For each fld in rs.Fields
        if fld.type = 'autoIncrement?'
            Exit for
        End If
    Next fld
    GetID = fld.Name
End Sub

I tried looking online but I couldn't find a dao field type for AutoIncrement. I noticed there is a type called DbGuid That seems to have something to do with this, but I can't figure out what it is. I Also saw other sql DBMS that have a function for this sort of thing, but I couldn't find such a function in MS Access.

It is a big database and I don't know what the AutoIncrement field's name might be. So I can't do a instr(fieldname, "id") or something like that, to find it.


Solution

  • The attributes field can be a combination of a few values that become one total value see: MSDN and MSDN Forum

    I could not get dbUpdateableField to print out a value for any field but apparently it is 32.

    Attribute: dbAutoIncrField    Long: 16      Binary: 0000000000010000
    Attribute: dbDescending       Long: 1       Binary: 0000000000000001
    Attribute: dbFixedField       Long: 1       Binary: 0000000000000001
    Attribute: dbHyperlinkField   Long: 32768   Binary: 1000000000000000
    Attribute: dbSystemField      Long: 8192    Binary: 0010000000000000
    Attribute: dbUpdateableField  Long: 0       Binary: 
    Attribute: dbVariableField    Long: 2       Binary: 0000000000000010
    

    So since the field is a total your standard autoNum field will 17 for being dbAutoIncrField=16, and dbFixedField=1 so you could check fld.Attributes for a value of 17. The AND according to the linked post performs a bitwise And returning true if there is a one in the proper position.

    The result of fld.Attributes for your auto ID field is: Name: AutoID Attributes: 17 Binary: 0000000000010001 so you have a 1 in the position of dbAutoIncrField and a 1 in the position of the dbFixedField

    Private Function AutoNumberField(tableName As String) As String
         Dim dbs As DAO.Database
         Dim tdf As DAO.TableDef
         Dim fld As DAO.Field
    
         Set dbs = CurrentDb
         Set tdf = dbs.TableDefs(tableName)
         For Each fld In tdf.fields
             If fld.Attributes And dbAutoIncrField Then
                 AutoNumberField = fld.name
                 Exit Function
             End If
         Next fld
    End Function