Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim idx As DAO.Index
'Open the database
Set db = DBEngine.OpenDatabase("C:\nwind.mdb")
Set tbl = db.TableDefs("Contacts")
' Create the Primary Key and append table columns to it.
Set idx = tbl.CreateIndex("rimaryKey")
idx.Primary = True
idx.Fields.Append idx.CreateField("ContactId")
' Append the Index object to the Indexes collection of the TableDef.
tbl.Indexes.Append idx
db.Close
End Sub
ADOX
Sub ADOCreatePrimaryKey()
Dim cat As New ADOX.Catalog
Dim tbl As ADOX.Table
Dim pk As New ADOX.Key
' Open the catalog
cat.ActiveConnection = "rovider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\nwind.mdb;"
Set tbl = cat.Tables("Contacts")
' Create the Primary Key and append table columns to it.
pk.Name = "rimaryKey"
pk.Type = adKeyPrimary
pk.Columns.Append "ContactId"
' Append the Key object to the Keys collection of Table
tbl.Keys.Append pk