如何使用OpenRecordSet?

问题描述 投票:1回答:1

我正在尝试使用OpenRecordSet

参数是查询:

Select * FROM Batiments WHERE Type = "2";

如果我把它写成一个查询,它可以很好地工作。

但是使用OpenRecordSet我收到此错误:

Object variable or With block variable not set

我不明白什么是错的,从我看到的类似案例的所有教程中,我的语法应该是正确的。

这是完整的代码:

temp = "Select * FROM Batiments WHERE Type = " & Chr(34) & txtNouveauBatiment.Value & Chr(34) & ";"
        rstBatiment.OpenRecordset tmp

        If (rstBatiment.EOF) Then
            Set dbs = CurrentDb
            Set rstBatiment = dbs.OpenRecordset("Batiments")

            rstBatiment.AddNew
            rstBatiment!Type = txtNouveauBatiment.Value
            rstBatiment.Update

            Refresh
        End If
vba ms-access
1个回答
1
投票

记录集对象上的.OpenRecordset方法不打算打开新记录集,而是打开基于打开记录集的过滤记录集(使用.Filter属性)。

如果要打开新记录集,则需要使用CurrentDb.OpenRecordset

temp = "Select * FROM Batiments WHERE [Type] = " & Chr(34) & txtNouveauBatiment.Value & Chr(34) & ";"
Set dbs = CurrentDb
Set rstBatiment = dbs.OpenRecordset(temp)

If (rstBatiment.EOF) Then
    Set rstBatiment = dbs.OpenRecordset("Batiments")
    rstBatiment.AddNew
    rstBatiment!Type = txtNouveauBatiment.Value
    rstBatiment.Update
    Refresh
End If

请注意,我并没有真正得到Refresh线。如果您要刷新表单,通常会指定您在当前表单对象上执行方法,例如Me.Refresh

另请注意,Type是Access SQL中的reserved words之一,因此需要括起来

© www.soinside.com 2019 - 2024. All rights reserved.