【问题标题】:Why am I getting a run-time error 3021 (no current record) when trying to delete the current record from an Access form?尝试从 Access 表单中删除当前记录时,为什么会收到运行时错误 3021(无当前记录)?
【发布时间】:2017-09-08 22:07:51
【问题描述】:

我在主窗体上的“取消”按钮的单击事件中附加了以下 VBA 代码。目的是先删除“entities_subform”中的所有记录,然后再删除主表单中的相关记录。

但是,虽然子表单中的实体已成功删除,但由于运行时错误 3021(无当前记录),主表单记录并未删除。

我需要做什么才能有效地将焦点重新设置在主窗体上以使其正常工作?在我添加代码以从实体子表单中删除记录之前,命令acCmdDeleteRecord 在主表单中运行良好。我已经尝试在下面的acCmdDeleteRecord 之前插入行Me.SetFocus,但这没有任何区别。

Private Sub Cancel_New_Record_Click()
    If MsgBox("Are you sure you want to delete this record?", vbYesNo) = vbYes Then

        'first we need to delete all the entities in the subform, to prevent orphans being left behind
        entities_subform.SetFocus

        Dim entityRecSet As Recordset
        Set entityRecSet = entities_subform.Form.Recordset.Clone()
        entityRecSet.Delete
        entityRecSet.Close
        Set entityRecSet = Nothing

        'now we can delete the check record
        DoCmd.RunCommand acCmdDeleteRecord
        DoCmd.Close acForm, "checks"
        DoCmd.OpenForm "menu"
    End If

End Sub

编辑:现在我已经能够通过使用以下来实现我正在寻找的功能:

Private Sub Cancel_New_Record_Click()
    '--------------------------------------------------
    'deletes the newly created record from the database
    '--------------------------------------------------
    If MsgBox("Are you sure you want to delete this record?", vbYesNo) = vbYes Then

        'grab the id of the current check record for later
        Dim checkID As Integer
        checkID = Me.Check_ID

        'delete the current check record
        DoCmd.RunCommand acCmdDeleteRecord

        'now delete any orphan entities from the entity table
        CurrentDb.Execute "DELETE * FROM entities WHERE entities.[Check ID] = " & checkID & ";"

        'close the form and return to the menu
        DoCmd.Close acForm, "checks"
        DoCmd.OpenForm "menu"
    End If

End Sub

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

    首先,这只是创建记录的克隆:

    Set entityRecSet = entities_subform.Form.Recordset.Clone()
    

    然后,这只是删除克隆的第一条记录并关闭克隆:

    entityRecSet.Delete
    entityRecSet.Close
    

    因此,您的记录保持不变。

    您可以并且应该做的是在两个表之间设置参照完整性。那么在删除主记录时,所有的子记录都会被自动删除。

    【讨论】:

    • 有趣的是,记录正在从实体表中删除,即使我只是在操作记录集的克隆。我将研究参照完整性,因为我以前没有使用过它。目前,我已经能够实现我需要的功能,使用 SQL 查询在从主窗体中删除记录后编辑实体表。
    猜你喜欢
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    相关资源
    最近更新 更多