ms访问将多行插入父子表

时间:2015-04-25 21:33:51

标签: access-vba

您好我一直在尝试将先前的堆叠溢出帖子调整到我的情况但是做得很短。我在父子关系中有2 ms访问表(一对多)。我试图写一些vba将1条记录插入父表,将多条记录插入子表。我看到这篇文章做了一些接近我想要的东西,但它是一对一的关系。有人可以给我一个如何在子表中使用多行进行此操作的示例吗?

How can I make new records cascade across a one to one relationship in MS Access?

我正在使用MS Access 2010,并且我将vba作为MS Excel 2010中的模块编写。

1 个答案:

答案 0 :(得分:1)

这一切都与你如何连接"很多"条目表到"一个"表。 (除非我错过了你的问题。)这个例子用来说明:

Option Explicit

Sub AddClassWithStudents()
    Dim tblClass As Recordset
    Dim tblStudents As Recordset
    Dim db As database
    Dim classID As Long
    Dim newKids() As String
    Dim kid As Variant

    Set db = DBEngine(0).OpenDatabase("Database1.accdb")
    Set tblClass = db.openrecordset("tblClasses", dbopendynaset)
    Set tblStudents = db.openrecordset("tblStudents", dbopendynaset)

    '--- add a new class
    tblClass.AddNew
    tblClass("Title").Value = "Calculus"
    tblClass("Teacher").Value = "Einstein"
    tblClass.Update
    tblClass.Bookmark = tblClass.LastModified  'makes it the current record
    classID = tblClass("ID").Value

    '--- add some students
    newKids = Split("Tom,Dick,Harry,Suzie,Mary", ",", , vbTextCompare)
    For Each kid In newKids
        tblStudents.AddNew
        tblStudents("ClassID").Value = classID
        tblStudents("StudentName").Value = kid
        tblStudents.Update
    Next kid

    db.Close
    Set tblStudents = Nothing
    Set tblClass = Nothing
    Set db = Nothing
End Sub