"Compile error: qualifier must be a collection" error when trying to update record ID with recordset Bookmark

"Compile error: qualifier must be a collection" error when trying to update record ID with recordset Bookmark

如何解决下面代码中指定行的 "Compile error: qualifier must be a collection"?

我基本上有两个table:itemsIDtitleamount)和relationshipsparentId, clientId).我基本上只是在这里尝试在 items 中创建一条新记录,然后也创建一条新的 relationships table 记录。

我不确定如何将新 items 记录(刚刚创建)分配给新 relationships 记录的 childId 字段。

Private Sub Command18_Click()
    Debug.Print ("*** Starting ***")

    ' New Record
    Dim rsItems As Recordset
    Set rsItems = CurrentDb.OpenRecordset("items")
    rsItems.AddNew
    rsItems![title] = "title"
    rsItems![amount] = 123
    rsItems.Update

    ' Get new ID
    rsItems.Bookmark = rsItems.LastModified
    newId = rsItems.Bookmark
    Debug.Print ("New ITEM record with ID " & newId)

    ' Relationships
    Dim rsRelationship As Recordset
    Set rsRelationship = CurrentDb.OpenRecordset("relationships")
    rsRelationship.AddNew
    'Debug.Print ("Relationships Field Types: " & TypeName(gcItemParentId) & ", " & TypeName(rsItems.LastModified!ID))
    rsRelationship![parentId] = gcItemParentId  'taken from text box on main form that holds current parent ID
    rsRelationship![clientId] = rsItems.LastModified!["ID"] ' *** ERROR HERE *** 
    rsRelationship.Update

    ' Get new ID
    rsRelationship.Bookmark = rsRelationship.LastModified
    newId = rsItems.Bookmark
    Debug.Print ("New RELATIONSHIP record with ID " & newId)

    ' Refresh Form
    Me.Refresh

    ' Cleanup
    rsItems.Close
    rsRelationship.Close
    Set rsItems = Nothing
    Set rsRelationship = Nothing

End Sub

您收到此错误是因为您试图使用 LastModifiedBookmark 来表示记录中的 ID 而不仅仅是记录集中的记录位置。他们做不到。

因此,您需要 newId = rsItems!ID 而不是 newId = rsItems.Bookmark。获得刚刚添加的记录的主键后,您将与 rsRelationship!clientId = newId 一起使用它。 (您可能还应该向 Relationships table 添加一个名为 RelationshipID [尽管名称并不重要] 的主键字段。在 Access 中,所有具有 table 的可执行关系 [在访问意义上] 必须具有主键,并且通常几乎所有 tables 都应该拥有它们,无论他们在技术上是否需要它们。主要是因为所有 tables 理论上都可以具有可执行关系应该;Access 在维护数据完整性和创建易于使用的链接方面比手写代码通常要好得多。)

整个代码看起来像这样,删除了调试语句、错误处理和冗余注释:

Private Sub Command18_Click()
    Dim rsItems As Recordset
    Set rsItems = CurrentDb.OpenRecordset("items")
    rsItems.AddNew
    rsItems!title = "title"
    rsItems!amount = 123
    rsItems.Update
    ' Go back to the record we just saved
    rsItems.Bookmark = rsItems.LastModified
    newId = rsItems!ID

    Dim rsRelationship As Recordset
    Set rsRelationship = CurrentDb.OpenRecordset("relationships")
    rsRelationship.AddNew
    rsRelationship!parentId = gcItemParentId
    rsRelationship!clientId = newId
    rsRelationship.Update

    Me.Refresh

    rsItems.Close
    rsRelationship.Close    
End Sub