ADO - MoveFirst and MoveLast
MoveFirst and MoveLast methods are used to navigate within a Recordset. They move the record pointer to the first or last record, respectively.
1. MoveFirst
-
Purpose: Moves the record pointer to the first record in the Recordset.
-
Syntax:
rs.MoveFirst -
Usage Notes:
-
Used when you want to start reading from the beginning of the Recordset.
-
Will cause an error if the Recordset does not support backward movement (for example, if the cursor type is
adForwardOnly). -
Before using, it’s a good practice to check that the Recordset is not empty:
If Not (rs.BOF And rs.EOF) Then rs.MoveFirst End If
-
2. MoveLast
-
Purpose: Moves the record pointer to the last record in the Recordset.
-
Syntax:
rs.MoveLast -
Usage Notes:
-
Useful when you need to access the most recent record or display the total count of records.
-
Like
MoveFirst, it can only be used if the Recordset supports backward navigation. -
Example:
If Not (rs.BOF And rs.EOF) Then rs.MoveLast MsgBox "Last record: " & rs("EmployeeName") End If
-
3. Cursor Type Requirement
To use MoveFirst, MoveLast, MovePrevious, etc., the Recordset must have a scrollable cursor type.
For example:
rs.Open "SELECT * FROM Employees", conn, adOpenStatic, adLockReadOnly
Here, adOpenStatic supports both forward and backward navigation.
4. Summary Table
| Method | Moves Pointer To | Requires Scrollable Cursor | Typical Use |
|---|---|---|---|
MoveFirst |
First record | Yes | Start reading from beginning |
MoveLast |
Last record | Yes | Go directly to end or count total records |