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.