So take the following example:
Sub CreateRelation()
Dim db As Database
Dim rel As Relation
Dim fld As Field
Set db = CurrentDb
Set rel = db.CreateRelation("OrderID", "Orders", "Products")
'referential integrity
rel.Attributes = dbRelationUpdateCascade
'specify the key in the referenced table
Set fld = rel.CreateField("OrderID")
fld.ForeignName = "OrderID"
rel.Fields.Append fld
db.Relations.Append rel
End Sub
I keep getting the error:
No unique index found for the referenced field of the primary table.
If I include the vba before this sub to create in index on the field, it gives me the error:
Index already exists.
So I am trying to figure this out. If there are not any primary keys set, will that cause this to not work? I am confused by this, but I really really want to figure this out. So orderID
is a FOREIGN KEY in the Products
Table
You can create a relationship manually through the interface, then reverse engineer it. Here is an Immediate Window session where I examined an existing relationship:
For reference, this is the sub used to create that relationship:
Don't bother with the dbRelationUpdateCascade attribute until after you confirm you have sorted out which are the foreign table and key.
The error "No unique index found for the referenced field of the primary table" is caused by the fact that
OrderId
must not be the primary key of the Orders table and it must not have a unique index on it.The other errors "Index already exists" are caused by the fact that Access will add a non-unique index to a foreign key when it is created. It is likely that there is already an index in the Products table called "OrderId" and it is creating a collision when you try to create the foreign key via code. You need to check the
TableDef.Indexes
collection on the Products table to ensure that an index called "OrderId" does not already exist before you add the foreign key.