Microsoft Access: Programmatically get the primary key of a database table

Platform:Microsoft Access
Task:Programmatically get the primary key of a database table
Discussion:
You need to get the primary key of an Access table using code
Example:
'call the function below like so: fFindPrimaryKeyFields(CurrentDB.TableDefs("MyTable"))
Function fFindPrimaryKeyFields(tdf As TableDef) As String
    Dim idx As Index
    On Error GoTo HandleIt
    For Each idx In tdf.Indexes
        If idx.Primary Then
            fFindPrimaryKeyFields = idx.Fields
            GoTo OutHere
        End If
    Next idx
OutHere:
    Set idx = Nothing
    Exit Function
HandleIt:
    Select Case err
        Case 0
            Resume Next
        Case Else
            'MsgBox err & " " & err.Description, vbCritical + vbOKOnly, "Error"
            fFindPrimaryKeyFields = vbNullString
        Resume OutHere
    End Select
End Function
Back to Index