如何在 DAO 记录集中查找和删除记录,其中两个记录值等于表单上的两个单独的组合框

How can one find and delete a record in a DAO Recordset where two record values are equal to two separate combo boxes on a form

我有一个 ACCESS 2010 表格:

Activity 花名册 table 看起来像这样:

我想从给定的 activity 中删除一个成员,并开发了一些我认为很接近但无法解决关键问题的代码。我必须在 Activity 花名册 table 中找到包含 ActivityID 和 MemberID 值的记录的行,这些值对应于“Activity 名称”组合框和“删除成员”组合框。这是代码:

Private Sub cmdRemoveMember_Click()

Dim MembeID As Long, CutMemID As Long, ActID As Long
Dim db As DAO.Database, rsIn As DAO.Recordset, rsOut As DAO.Recordset
Set db = CurrentDb
Dim strQName As String


CutMemID = Me!cboCutMember.Column(0)  'set the value of CutMemID as the MemberID from the Remove Member combo box
ActID = Me.cboActivityName.Column(0)  'store the ActID from the Activity Name combo box

'query the tblActivityRoster for records with specified Activity ID (Name)- this generates the QActivityMembership query
strQName = "SELECT * FROM [tblActivityRoster] WHERE [ActivityID] = " & ActID
Set rsIn = db.OpenRecordset(strQName, dbOpenDynaset, dbReadOnly)
rsIn.MoveLast  'this will "populate the recordset"


'prepare to remove a member from the tblActivityRoster
Set rsOut = db.OpenRecordset("tblActivityRoster", dbOpenDynaset, dbEditAdd)
rsOut.MoveLast   'this will "populate the recordset"

With rsOut  'from the tblActivityRoster, find the record where the Activity ID = ActID and MemberID = CutMemID
    Do Until rsOut.EOF
        If rsOut![ActivityID] = ActID And rsOut![MemberID] = CutMemID Then   'THIS IS WHERE IF FAILS!!
            rsOut.Delete
        End If
        rsOut.MoveNext
    Loop

End With

Me.QActivityMembership_subform.Form.Requery

'Now close the query
DoCmd.Close acQuery, strQName

'now clear everything
rsIn.Close
rsOut.Close
Set rsIn = Nothing
Set rsOut = Nothing
Set db = Nothing

End Sub

非常感谢任何帮助……谢谢!

迈克尔,

您的代码看起来绕了很长一段路。为什么不直接使用 DELETE 查询呢?示例:

Private Sub cmdRemoveMember_Click()

Dim CutMemID As Long, ActID As Long, strQName As String

Dim db As DAO.Database
Set db = CurrentDb

CutMemID = Me!cboCutMember.Column(0)  'set the value of CutMemID as the MemberID from the Remove Member combo box
ActID = Me.cboActivityName.Column(0)  'store the ActID from the Activity Name combo box

' build delete query for Activity and Member
strQName = "DELETE FROM [tblActivityRoster] WHERE ([ActivityID] = " & ActID & ") AND ([MemberID] = " & CutMemID & ");"

' delete all matching records
db.Execute strQName, dbSeeChanges + dbFailOnError

Me.QActivityMembership_subform.Form.Requery

Set db = Nothing

End Sub

更直接。