VBA访问无当前记录错误

时间:2017-06-08 21:50:55

标签: vba access-vba ms-access-2010

我似乎无法弄清楚这个错误,我想要的只是继续我想要包含在电子邮件中的下一个项目。

我正在使用查询通过Access发送电子邮件。

Dim MyDb As DAO.Database
Dim rsEmail As DAO.Recordset
Dim InfoQuery As DAO.Recordset
Dim secondQuery As DAO.Recordset


Dim sToName As String
Dim sSubject As String
Dim sMessageBody As String
Dim test As String
Dim test2 As String

Set MyDb = CurrentDb()
Set rsEmail = MyDb.OpenRecordset("firstEmailCAD", dbOpenSnapshot)
Set InfoQuery = MyDb.OpenRecordset("InformationTableQueryEmail", dbOpenSnapshot)
Set secondQuery = MyDb.OpenRecordset("secondEmailCAD", dbOpenSnapshot)

test = rsEmail.Fields(2)
test2 = ""

With rsEmail

        If IsNull(test) Then
           test2 = test2 & "0"
        End If

        InfoQuery.MoveFirst
        Do Until rsEmail.EOF
            If IsNull(InfoQuery.Fields(0)) = False Then
                sToName = InfoQuery.Fields(0)
                sSubject = "Earnings for: " & InfoQuery.Fields(1)
                sMessageBody = "Email Body Text " & vbCrLf & _
                    "Field A: " & .Fields(1) & vbCrLf & _
                    **"Field B: " & test2 & vbCrLf & _**
                    "Field C: " & secondQuery.Fields(2)

                DoCmd.SendObject acSendNoObject, , , _
                    sToName, , , sSubject, sMessageBody, False, False
            End If
            .MoveNext
        Loop
End With

Set MyDb = Nothing
Set rsEmail = Nothing
Set InfoQuery = Nothing
Set secondQuery = Nothing

所以rsEmail查询目前没有记录,它取决于它是否有记录的日期,但我想要做的是能够将0分配给该查询的特定列

test = rsEmail.Fields(2) - >考虑到我只在if语句中使用它,所以这给出了一个错误,因为我没有当前记录,因此我可以在创建消息时输入0

我是VBA Access的新手,任何帮助都将不胜感激:)

谢谢,

1 个答案:

答案 0 :(得分:2)

如韦恩所说,您应该在命令之前检查一下是否有记录

InfoQuery.MoveFirst

通常最好同时检查.BOF和.EOF

所以会是这样:

If Not (InfoQuery.EOF And InfoQuery.BOF) Then
  InfoQuery.MoveFirst
  .....
Else
  'manage the lack of records condition here
  ....
End If

如果记录集没有记录,则BOF和EOF都设置为true