Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim fieldName As Variant
DoCmd.RunSQL "CREATE TABLE MyTables([TableName] VARCHAR(50))"
DoCmd.RunSQL "CREATE TABLE MyRelations([RelationName] VARCHAR(50), [Attributes] VARCHAR(50), [TableName] VARCHAR(50), [ForeignName] VARCHAR(50))"
DoCmd.RunSQL "CREATE TABLE MyRelationFields([RelationName] VARCHAR(50), [Field] VARCHAR(50), [Foreign] VARCHAR(50))"
DoCmd.RunSQL "INSERT INTO MyTables(TableName) SELECT name from MSysObjects where type = 1 and flags = 0 and name not in('MyTables','MyRelations','MyRelationFields')"
For Each rel In CurrentDb.Relations
DoCmd.RunSQL "INSERT INTO MyRelations(RelationName, Attributes, TableName, ForeignName) VALUES('" & rel.Name & "','" & rel.Attributes & "','" & rel.Table & "','" & rel.ForeignTable & "')"
For Each fld In rel.Fields
DoCmd.RunSQL "INSERT INTO MyRelationFields(RelationName, Field, Foreign) VALUES('" & rel.Name & "','" & fld.Name & "','" & fld.ForeignName & "')"
Next
Next
While CurrentDb.Relations.Count > 0
With CurrentDb
For Each rel In .Relations
.Relations.Delete rel.Name
Next
End With
Wend
Set db = CurrentDb()
Set rs = db.OpenRecordset("select TableName from MyTables")
While Not rs.EOF
DoCmd.RunSQL "Delete * from [" & rs.Fields("TableName") & "]"
DoCmd.TransferDatabase acImport, "Microsoft Access", Me.ImportPath, acTable, rs.Fields("TableName"), "TempTable"
DoCmd.RunSQL "INSERT INTO [" & rs.Fields("TableName") & "] SELECT * from TempTable"
DoCmd.RunSQL "DROP TABLE TempTable"
rs.MoveNext
Wend
rs.Close
Set rs = db.OpenRecordset("select * from MyRelations")
With CurrentDb
While Not rs.EOF
Set rel = .CreateRelation(rs.Fields("RelationName"), rs.Fields("TableName"), rs.Fields("ForeignName"), rs.Fields("Attributes"))
If DCount("Field", "MyRelationFields", "RelationName = '" & rs.Fields("RelationName") & "'") < 2 Then
fieldName = DLookup("Field", "MyRelationFields", "RelationName = '" & rs.Fields("RelationName") & "'")
rel.Fields.Append rel.CreateField(fieldName)
rel.Fields(fieldName).ForeignName = fieldName
Else
Set rs2 = db.OpenRecordset("select Field from MyRelationFields where RelationName = '" & rs.Fields("RelationName") & "'")
While Not rs2.EOF
rel.Fields.Append rel.CreateField(rs2.Fields("Field"))
rel.Fields(rs2.Fields("Field")).ForeignName = rs2.Fields("Foreign")
rs2.MoveNext
Wend
rs2.Close
End If
.Relations.Append rel
rs.MoveNext
Wend
End With
rs.Close
DoCmd.RunSQL "DROP TABLE MyRelationFields"
DoCmd.RunSQL "DROP TABLE MyRelations"
DoCmd.RunSQL "DROP TABLE MyTables"