I need to set relationships using vba. However in Access 365 the DAO lib is not working in reference. So I comment out the DIM and then it seems to work. However, the line ".Attributes = dbRelationUpdateCascade + dbRelationDeleteCascade" is NOT working. No error, but no cascading. How can I put then on as well? And if you have a better option by NOT using DAO of some other trick, that would be great. Hier is the code:
Sub CreateRelationDAO() Dim db As DAO.Database Dim rel As DAO.Relation Dim fld As DAO.Field
'Initialize Set db = CurrentDb()
'Create a new relation. Set rel = db.CreateRelation("MyMainTableMyRelatedTable")
'Define its properties. With rel 'Specify the primary table. .Table = "MyMainTable" 'Specify the related table. .ForeignTable = "MyRelatedTable" 'Specify attributes for cascading updates and deletes. .Attributes = dbRelationUpdateCascade + dbRelationDeleteCascade
'Add the fields to the relation. 'Field name in primary table. Set fld = .CreateField("MyMainTableID") 'Field name in related table. fld.ForeignName = "MyForeignKeyID" 'Append the field. .Fields.Append fld
'Repeat for other fields if a multi-field relation.
End With
'Save the newly defined relation to the Relations collection. db.Relations.Append rel
'Clean up Set fld = Nothing Set rel = Nothing Set db = Nothing Debug.Print "Relation created." End Sub
Kevin Robertson
@Reply 3 years ago
Sounds like you may be missing a reference.
Go to Tools--References and make sure this reference is selected:
Microsoft Access 16.0 Access database engine Object Library
I have tested you code and it worked for me.
A few things to consider I made some changes so that nothing was hard coded in the VBA (Everything was sent from form fields).
I also added some error handling.
If you are a Visitor, go ahead and post your reply as a
new comment, and we'll move it here for you
once it's approved. Be sure to use the same name and email address.
This thread is now CLOSED. If you wish to comment, start a NEW discussion in
Visitor Forum.