读取数据库并缺少最后一个条目时,运行时错误3201

时间:2018-07-16 16:17:06

标签: vba ms-access

我目前正在努力处理这段代码:

While receiver = data.Fields("Contact")
    If first Then
        first = False
        strSig = Replace(strSig, ID, data.Fields("ID") & ID)
    Else
        strSig = Replace(strSig, ID, ", " & data.Fields("ID") & ID)
    End If

    data.MoveNext
Wend

它没有读取最后一个数据库条目。

我的完整代码正在执行以下操作:

  1. 读取数据库
  2. 读取HTML文件
  3. 搜索一个人的多个ID并将其汇总
  4. 将ID替换为ID中的占位符
  5. 发送电子邮件

除了最后一个条目外,该过程确实有效。对于该条目,我收到一个

  

3021运行时错误-没有当前记录。

1 个答案:

答案 0 :(得分:2)

这是一个如何遍历记录集的示例:

Option Explicit

Sub recordsetDemo()

    'can use the name of a table or of a query, or a specific SQL query:
    Const rs_Source = "select * from tblYourTable"

    Dim rs As Recordset
    Set rs = CurrentDb.OpenRecordset(rs_Source) 'open the recordset
    With rs  'refer to the RS with "." dots instead of the full name "rs."
        If Not .EOF Then .MoveFirst 'move to the first record
        Do While Not .EOF 'keep doing this until the end of the recordset


            Debug.Print !myField1, !myField2  'do "something" here with the data.


            .MoveNext 'move to the next record
        Loop 'loop will end if there's no "next record"
        .Close 'close the recordset
    End With
    Set rs = Nothing 'clear the variable

End Sub

使用您的示例进行粗略修改:

Sub recordsetDemo()

    Dim data As Recordset
    Set data = CurrentDb.OpenRecordset("YourTableOrQueryName") 'open recordset

  '***however you setup your "Data" recordset could replace the above code***

    With data
        If .EOF Then 'check if there's data
            MsgBox "No Data Found!"
            Exit Sub
        End If

        .MoveFirst 'move to the first record
        Do While Not .EOF 'keep doing this until the end of the recordset

            If first Then
                first = False
                strSig = Replace(strSig, id, !id & id)
            Else
                strSig = Replace(strSig, id, ", " & !id & id)
            End If

            .MoveNext 'move to the next record

        Loop 'loop will end if there's no "next record"
        .Close 'close the recordset
    End With
    Set rs = Nothing 'clear the variable
End Sub

鉴于您提供的信息,这就是我所能做的。