I'm trying to learn how to create a relation via vba and am receiving error 3609 "No unique index found for the reference field of the primary table."
Here is the Function I am testing (to create a new table, new fields, new index, new relation):
Public Function VBATestUpdateProgram() As Boolean
' This function will test the new table-building, including index (ID) assignment and relations.
On Error GoTo Error_Handler
Dim dbsTestVBA As DAO.Database
Dim tdfTestVBA As DAO.TableDef
Dim idxID As DAO.Index
Dim fldID As DAO.Field
Dim fldStateLookUp As DAO.Field
Dim fld As DAO.Field
Dim relState As DAO.Relation
Set dbsTestVBA = CurrentDb
Set tdfTestVBA = dbsTestVBA.CreateTableDef("TestVBATableBuilding")
Set fldID = tdfTestVBA.CreateField("ID", dbLong)
Set fldStateLookUp = tdfTestVBA.CreateField("StateLookUp", dbLong)
fldID.Attributes = dbAutoIncrField
tdfTestVBA.Fields.Append fldID
tdfTestVBA.Fields.Append fldStateLookUp
Set idxID = tdfTestVBA.CreateIndex("TestVBATableBuilding_ID")
idxID.Primary = True
idxID.Unique = True
Set fldID = idxID.CreateField("ID")
idxID.Fields.Append fldID
tdfTestVBA.Indexes.Append idxID
dbsTestVBA.TableDefs.Append tdfTestVBA
dbsTestVBA.TableDefs.Refresh
Application.RefreshDatabaseWindow
Set relState = dbsTestVBA.CreateRelation("TestVBATableBuildingSta teNames", "TestVBATableBuilding", "StateNames")
relState.Attributes = dbRelationUpdateCascade Or dbRelationDeleteCascade
Set fld = relState.CreateField("StateLookUp")
fld.ForeignName = "StateName"
relState.Fields.Append fld
dbsTestVBA.Relations.Append relState
dbsTestVBA.Relations.Refresh
Application.RefreshDatabaseWindow
Set fldID = Nothing
Set fldStateLookUp = Nothing
Set fld = Nothing
Set idxID = Nothing
Set tdfTestVBA = Nothing
Set relState = Nothing
VBATestUpdateProgram = True
Set dbsTestVBA = Nothing
Exit_Procedure:
Exit Function
Error_Handler:
MsgBox "An error has occurred in this application. Please contact your technical" _
& " support and tell them the following information:" & vbCrLf & vbCrLf _
& "Error Number " & Err.Number & ", " & Err.Description, Buttons:=vbCritical
Resume Exit_Procedure
End Function
"StateNames" is an existing table with the following fields:
ID (primary key and auto-numbered)
StateName (text, 25)
StateAbbrev (text, 2)
My intent, here, is to have the newly-created "StateLookUp" field be a "LookUp", or at least be related to, the "StateName" field in the "StateNames" table, where each "StateName" is unique (i.e., "StateLookUp" is 'many'; "StateName" is 'one'). After receiveing the error, the "TestVBATableBuilding" table is built, as well as both the "ID" primary key and "StateLookUp" fields.
Help, Mr. Wizard!
