>
Function ForeignNameTable () As Integer
Dim dbsDefault As Database
Dim fldLocal As Field, relForeign As Relation
' Get database.
Set dbsDefault = _
DBEngine.Workspaces(0).OpenDatabase("Northwind.mdb")
' Create new relationship and set its properties.
Set relForeign = dbsDefault.CreateRelation("MyRelation")
relForeign.Table = "Table1"
relForeign.ForeignTable = "Table2"
' Create field and set its properties.
Set fldLocal = relForeign.CreateField("Field1")
fldLocal.ForeignName = "Field2"
' Append field to relation and relation to database.
relForeign.Fields.Append fldLocal
dbsDefault.Relations.Append relForeign
dbsDefault.Close
End Function
Example (Microsoft Access)
The following example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables — in this case, Employees (the primary table) and Orders (the foreign table) in the current database. EmployeeID is the primary key in the Employees table, and also a foreign key in the Orders table. The relationship is one-to-many and referential integrity is enforced.
To test the following example in Microsoft Access, open the Northwind database and click Relationships on the Tools menu. Delete the relationship between the Employees table and the Orders table. Close the Relationships window, saving the current configuration when prompted. Then run the following procedure from a standard module, and view the Relationships window again to see the new relationship.
Sub ForeignNameTable()
Dim dbs As Database
Dim fld As Field, rel As Relation
' Return Database variable that points to current database.
Set dbs = CurrentDb
' Create new relationship and set its properties.
Set rel = dbs.CreateRelation("EmployeesRelation")
' Denote primary table.
rel.Table = "Employees"
' Denote foreign table.
rel.ForeignTable = "Orders"
rel.Attributes = dbRelationUpdateCascade + dbRelationDeleteCascade
' Create field in Fields collection of Relation.
Set fld = rel.CreateField("EmployeeID")
' Provide name of foreign key field.
fld.ForeignName = "EmployeeID"
' Append field to Relation and Relation to database.
rel.Fields.Append fld
dbs.Relations.Append rel
End Sub