Dim dbsNorthwind As Database
Dim tdfEmployees As TableDef
Dim idxLoop As Index Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set tdfEmployees = dbsNorthwind!Employees With tdfEmployees ' Enumerate Indexes collection of Employees
' table.
For Each idxLoop In .Indexes
If idxLoop.Primary Then Debug.Print " Primary Key:";
Debug.Print " " & idxLoop.Name
Next idxLoop
End With dbsNorthwind.Close
Dim tdfEmployees As TableDef
Dim idxLoop As Index Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set tdfEmployees = dbsNorthwind!Employees With tdfEmployees ' Enumerate Indexes collection of Employees
' table.
For Each idxLoop In .Indexes
If idxLoop.Primary Then Debug.Print " Primary Key:";
Debug.Print " " & idxLoop.Name
Next idxLoop
End With dbsNorthwind.Close
下面是ADO方法:(这是微软网站上的例子)
Private Function FindPrimaryKey( _
tbl As ADOX.Table) As Variant
' Given a particular table, find the primary
' key name, if it exists.
' Returns the name of the primary key's index, if
' it exists, or Null if there wasn't a primary key.
Dim idx As ADOX.Index
For Each idx In tbl.Indexes
If idx.PrimaryKey Then
FindPrimaryKey = idx.Name
Exit Function
End If
Next idx
FindPrimaryKey = Null
End Function