Access 2007 VBA记录集无限循环

时间:2013-12-27 13:18:27

标签: ms-access-2007 access-vba

所以我正在进行一个查询,当你单击一个按钮时,它会获取一个带有未分配数据字段的记录集,并将该记录集复制到具有新“已分配版本”的同一个表中。

我希望我的数据库能够从原始未分配的集合中创建不同的/多个“分配的版本”,这在我创建第一个分配的集合时效果很好,但是当我尝试创建新的分配集合时,它会进入一个似乎完全随机的循环,它可以创建10-1000的新条目,我不知道是什么导致了这个。

很抱歉,如果这令人困惑,查看代码可能会有所帮助

谢谢!

Dim rs1 As DAO.Recordset
 Dim unionquery As String

 Dim CURRENT_SOFTWARE_VERSION As String

 CURRENT_SOFTWARE_VERSION = Me.Parent.[Software Version].Value

 initialquery = "select [Test Script] , [PROC_CHECK_ID], [Software Version] from (FORMAL_CERT_PROCEDURE_TEST_SCRIPTS inner join FORMAL_CERT_PROCEDURE_CHECK on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_PROCEDURE_CHECK.TEST_CASE_ID) inner join FORMAL_CERT_SOFTWARE_VERSION on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_SOFTWARE_VERSION.TEST_CASE_ID where PROC_CHECK_ID=" & Me.PROC_CHECK_ID & " AND [Software Version]=""" & CURRENT_SOFTWARE_VERSION & """ "

Set rs1 = CurrentDb.OpenRecordset(initialquery, dbOpenForwardOnly)

    Do Until rs1.EOF = True

        Dim rs2 As DAO.Recordset
        Set rs2 = CurrentDb.OpenRecordset( _
                  "SELECT * FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS", _
                  dbOpenDynaset)
        rs2.AddNew
        rs2![Test Script] = rs1![Test Script]
        rs2![PROC_CHECK_ID_FK] = rs1!PROC_CHECK_ID
        rs2![Software_Version] = rs1![Software Version].Value
        rs2![TEST_CASE_ID] = Me.TEST_CASE_ID
        rs2.Update
        rs2.Close
        Set rs2 = Nothing

        rs1.MoveNext

    Loop

1 个答案:

答案 0 :(得分:2)

亲爱的,亲爱的。 如果您将记录添加到当前正在迭代的表中,则在达到EOF时会遇到问题,因为您不仅要遍历开头的内容,还要迭代刚刚添加的新记录。

解决方案是将循环和插入分离为不连续的步骤:循环并保存要插入的值,然后在循环完成后插入。 假设值是字符串,数字,字符串,数字:

Set rs1 = CurrentDb.OpenRecordset(initialquery, dbOpenForwardOnly)
dim strQuery() as String
dim intCounter as Long
dim recordCount as Long
intCounter = 0
rs1.MoveLast
recordCount = rs1.RecordCount
Redim strQuery(0 to recordCount)
rs1.MoveFirst
strQuery(0) = "INSERT INTO FORMAL_CERT_PROCEDURE_TEST_SCRIPTS ([Test Script],[PROC_CHECK_ID_FK],[Software_Version],[TEST_CASE_ID]) VALUES "
Do Until rs1.EOF = True
    intCounter = intCounter + 1
    strQuery(intCounter) = strQuery(0) & " ('" & rs1![Test Script] & "'," & _
        & rs1!PROC_CHECK_ID & "," & _
        & "'" & rs1![Software Version].Value & "'," & _
        & Me.TEST_CASE_ID & ")"
    rs1.MoveNext

Loop

For intCounter = 0 To recordCount
    CurrentDb.Execute(strQuery(intCounter))
Next

这样可以避免在插入时EOF指针进一步移动的问题。

编辑:我忘了你不能用默认的DBA做多次插入,我改变了代码来反映这一点。