Getting primary key field name

J

John

Hi

Is it possible to programmatically get the name of the primary key field of
a recordset? Primary key is composed of a single field.

Thanks

Regards
 
J

Jellifish

Assuming the your table is named "tblAccessTable":

Debug.Print
CurrentDb.TableDefs("tblAccessTable").Indexes("PrimaryKey").Fields(0).Name
 
D

Dirk Goldgar

Jellifish said:
Assuming the your table is named "tblAccessTable":

Debug.Print
CurrentDb.TableDefs("tblAccessTable").Indexes("PrimaryKey").Fields(0).Name


There's no guarantee that the name of the primary index will be
"PrimaryKey", though it will be if you create it in the usual fashion, by
clicking the "key" icon in the table design toolbar. Here's a more generic
function, though, that doesn't rely on the name of the index (and that
returns multiple field names if the primary key is a compound index):

'----- start of code -----
Function PrimaryKeyFields(TableName As String) As String

Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim ix As DAO.Index
Dim fld As DAO.Field
Dim strFields As String

Set db = CurrentDb
Set tdf = db.TableDefs(TableName)
For Each ix In tdf.Indexes
If ix.Primary Then
For Each fld In ix.Fields
strFields = strFields & "," & fld.Name
Next fld
Exit For
End If
Next ix

If Len(strFields) > 0 Then strFields = Mid$(strFields, 2)

PrimaryKeyField = strFields

End Function

'----- end of code -----

If there is no primary key, a zero-length string is returned.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top