Search code examples
sqlvbaloopsms-access

Access VBA For Loop throwing error of "No Current Record" after 1 iteration of code


I have an Access database with a list of supervisors and employees. I would like to add a specific number of task records (number housed in a config table) for each employee. I loop through the table to get a list of supervisors, then loop through the table again for a list of employees (stored in separate record sets) - all working fine.

When I add the For Loop to the code, it will add the 1st supervisor and 1 task for each employee, then when it goes to move to the next iteration and add a second task for each employee, I get the error:

Run-time error '3021': No current record.

Something isn't jiving and I can't figure out why - code snip is below:

gSQL = "SELECT AssocID, Position, StatusCodeID FROM tblHistory WHERE (((tblHistory.Position) In (SELECT ConfigLongDesc FROM ref_Config WHERE ConfigShortDesc In ('Supervisors'))) AND tblHistory.StatusCodeID = '3')"

Set gRST = CurrentDb.OpenRecordset(gSQL)
...
    If gRST.RecordCount > 0 Then
        gRST.MoveFirst

        Do Until gRST.EOF
            aSQL = "SELECT AssocID, Position, StatusCodeID FROM tblHistory WHERE (((tblHistory.Position) In (SELECT ConfigLongDesc FROM ref_Config WHERE ConfigShortDesc In ('Employees'))) AND tblHistory.StatusCodeID = '3')"

            Set aRST = CurrentDb.OpenRecordset(aSQL)

            If aRST.RecordCount > 0 Then
                aRST.MoveFirst

                myCadence = DLookup("[ConfigLongDesc]", "ref_Config", "[ConfigShortDesc] = 'Frequency'")

                Do Until aRST.EOF
                    For i = 0 To myCadence

                        Debug.Print aRST!AssocID
                        aRST.MoveNext
                    Next i
                Loop
            End If
            gRST.MoveNext
        Loop
    End If
Else
    Exit Function
End If

Right now I am just printing the results to the immediate window, it will add the record set information after the issue with the error is fixed.


Solution

  • The phrases Do Until aRST.EOF and For i = 0 To myCadence could be in the wrong order.

    The execution of the sourcecode reaches For i = 0 and starts executing aRST.MoveNext, at least until aRST.EOF, at which point the execution has no problem going beyond aRST.EOF... The only test performed is on I <= myCadence, hence the execution goes beyond aRST.EOF ...

    I would suggest the following:

    For i = 0 To myCadence
        aRST.MoveFirst
        Do Until aRST.EOF
            Debug.Print aRST!AssocID
            aRST.MoveNext
        Loop
    Next i