访问VBA:对象无效或不再设置

Access VBA: object invalid or no longer set

我收到以下错误:

1
object invalid or no longer set

当我的代码运行以下字符串时:

1
DoCmd.RunCommand acCmdDeleteRecord

根据我的说法,我收到此错误,因为没有选择记录或选择的记录是Nothing

在执行代码之前如何添加支票?拥有这样的东西将是很棒的:

1
2
3
If SelectedRecord != Nothing then
   DoCmd.RunCommand acCmdDeleteRecord
End If

有多种方法可以解决此问题。

最简单的方法是打开控制向导,然后选择记录操作->删除记录。生成一个嵌入式宏。您可以使用它,也可以将其用作所需步骤的参考。

以下是一个完整的VBA解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Dim rs As Recordset: Set rs = Me.Recordset
With rs
    If Not rs.Updatable Then
        'RS is not updateable, delete will fail
        Exit Sub
    End If
    If Not .EOF And Not .BOF Then '0 records
        If Me.NewRecord Then
            If Not Me.Dirty Then
                'Do nothing, unchanged new record so won't be saved
            Else
                'Revert changes on new record
                Me.Undo
            End If
        Else
            .Delete
        End If
    End If
End With

请注意,我故意不使用DoCmd.RunCommand acCmdDeleteRecord。这是因为我希望能够指定要删除记录的表单(例如子表单)。