Creating Tables from VB Code - Primary Key

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I received a good response from Doug Steele about how to declare an
auto-increment field but I forgot to ask how to make it a Primary Key. I
figured it out from the Help using the Index-Object.Primary = True but then I
had a Many to Many Table where I want a Multi-Field Primary Key and I
couldn't see how to do this. I poured over the Help for 3 hours and tried
several things but came up dry. Can someone help me as to how to Define Two
Fields ( indexes ) as the Primary Key.?. Thanx for your help!!
 
The following code will create a primary index named MyIndex consisting of
two fields named Field1 and Field2 in an existing table MyJunctionTable.
Note that the name of the index is really irrelevant (other than the fact
that you can't have more than one index with the same name in a given table)

DIm dbCurr As DAO.Database
Dim tdfCurr As DAO.TableDef
Dim idxCurr As DAO.Index

Set dbCurr = CurrentDb
Set tdfCurr = dbCurr.TableDefs("MyJunctionTable")

With tdfCurr
Set idxCurr = .CreateIndex("MyIndex")
With idxCurr
.Fields.Append .CreateField("Field1")
.Fields.Append .CreateField("Field2")
.Primary = True
End With
.Indexes.Append idxCurr
End With
 
So simple I almost tripped over it. I didn't think about appending 2 fields
and then setting the .primary key. Thank you so much Doug.
 
Back
Top