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

Platform:Microsoft Access
Task:Programmatically get the primary key of a database table
You need to get the primary key of an Access table using code
'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
    Set idx = Nothing
    Exit Function
    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