循环以在Access VBA中创建表关系

时间:2018-03-26 11:46:16

标签: vba loops access relation

我尝试使用以下代码创建一个表关系,但它确实有效。

Dim rel As New Relation
Dim db As DAO.Database
Dim fld As DAO.Field

Set db = CurrentDb

rel.Attributes = dbRelationDontEnforce + dbRelationRight
rel.Name = "RelationName"
rel.Table = "tblParent"
rel.ForeignTable = "tblChild"

Set fld = rel.CreateField("FieldID")

fld.Name = "FieldID"
fld.ForeignName = "FieldID"
rel.Fields.Append fld
db.Relations.Append rel

当我试图循环它以从查询“QryRelaDict”创建多个关系时如下。它在第一个循环和第二个循环中创建了第一个关系,它在rel.Attributes = dbRelationEnforce处停靠run time error 3219: invalid operation。任何人都可以帮助循环创建现实吗?非常感谢。

   Dim db As DAO.Database
   Dim daRs As DAO.Recordset    
   Dim rel As New Relation
   Dim fld As DAO.Field

   Set db = CurrentDb
   Set daRs = db.OpenRecordset("QryRelaDict")

    Do While Not daRs.EOF

        Debug.Print daRs!tblPare & "-" & daRs!tblChil

        rel.Attributes = dbRelationEnforce 
        rel.Name = daRs!tblPare & "-" & daRs!tblChil & "-" & daRs!AAA
        rel.Table = daRs!tblPare
        rel.ForeignTable = daRs!tblChil

        Set fld = rel.CreateField(daRs!AAA)

        fld.Name = daRs!AAA
        fld.ForeignName = daRs!AAA

        rel.Fields.Append fld
        db.Relations.Append rel

        daRs.MoveNext
    Loop

1 个答案:

答案 0 :(得分:0)

这个问题需要答案。在评论中找到了它:

在循环中,添加Set rel = New Relation

示例:

   Dim db As DAO.Database
   Dim daRs As DAO.Recordset    
   Dim rel As Relation
   Dim fld As DAO.Field

   Set db = CurrentDb
   Set daRs = db.OpenRecordset("QryRelaDict")

   Do While Not daRs.EOF
        Set rel = New Relation
        Debug.Print daRs!tblPare & "-" & daRs!tblChil

        rel.Attributes = dbRelationEnforce 
        rel.Name = daRs!tblPare & "-" & daRs!tblChil & "-" & daRs!AAA
        rel.Table = daRs!tblPare
        rel.ForeignTable = daRs!tblChil

        Set fld = rel.CreateField(daRs!AAA)

        fld.Name = daRs!AAA
        fld.ForeignName = daRs!AAA

        rel.Fields.Append fld
        db.Relations.Append rel

        daRs.MoveNext
   Loop