Access 2013 编译错误 - 需要对象

Access 2013 Compile error - object required

我经常使用 Access,但只涉足 VBA 代码。我有一些有效的代码,但我尝试编译代码并收到以下错误。

Private Sub Report_Open(Cancel As Integer)
Dim RS As Date
Set RS = CurrentDb.OpenRecordset("tblDate")
MsgBox ("The month and year are: " & RS)
DoCmd.OutputTo acOutputReport, "LP Completions", "PDFFormat(*.pdf)", Chr(34) & "\sharepoint.xx.yyyy.zzz\Reports\" & Format(RS.Fields(0), "yyyy-mm") & Chr(32) & " - LP Completions - Exec Report.pdf" & Chr(34), False
End Sub

我收到编译错误:需要对象。在代码视图中,突出显示 RS =

我不知道为什么会出现这种情况。有人可以就如何解决这个问题提供一些指导吗?非常感谢!

在VBA中,Set仅在赋值给object变量时使用。 Date 类型的变量不是对象变量,所以你只需要说

RS = CurrentDb.OpenRecordset("tblDate")

(请注意,你 可以 ,如果你真的想,在前面放一个 Let,但几乎没有人这样做过)。

如果您打开一个记录集,变量应该是一个记录集。然后,您在消息框中引用 table 中的字段。

如果您在 table 中有多个记录,它将 return 第一个值 - 所以要么创建一个临时查询以 return 您想要的值,或者搜索记录集并转到正确的记录。

Private Sub Test()
    Dim RS As dao.Recordset
    Set RS = CurrentDb.OpenRecordset("tblDate")
    MsgBox "The month and year are: " & Format(RS.Fields("MyDateField"), "yyyy-mm")
End Sub

编辑: 如果您使用查询来获取记录:

Private Sub Test2()
    Dim qdf As DAO.QueryDef
    Dim rs As DAO.Recordset

    Set qdf = CurrentDb.CreateQueryDef("", "SELECT MAX(MyDateField) AS MaxDateField FROM tblDate")
    Set rs = qdf.OpenRecordset
    MsgBox "The month and year are: " & Format(rs.Fields("MaxDateField"), "yyyy-mm")
End Sub