Friday, 22 June 2012

5. MoveNext without testing EOF in VBA

MoveNext may take you to the end of the recordset (EOF) or a MovePrevious to the beginning of the recordset (BOF). Failure to test for these conditions means your code works for most cases, but generates an error one day when the last/first record is accessed.

The problem is prevalent when you have another exit condition in mind for your loop, so you are not thinking of EOF. Test for EOF (or BOF if moving backwards) before checking the real exit condition for your loop.


Use this construct for looping through Access recordsets:
    Do while Not rst.EOF
        If rst![MyField] <> Something Then  'The real loop exit condition.
            Exit Do
        End If
        ' Rest of your code here.

No comments:

Post a Comment