The RecordCount property returns a long value that indicates the number of records in a Recordset object.
Many a times you might have observed that RecordCount Property does not return a correct number instead it always returns a number -1.
RecordCount Property returns -1 because by default the Cursor is adOpenForwardOnly.
To get the exact Record Count from your RecordSet Object, you need to select the Cursor as adOpenKeyset or adOpenStatic
How to Set Cursor while establishing the Connection:
While establishing the connection to your Database, you can set the appropriate Cursor. The syntax is the same as shown in the below picture.
Syntax:
rs.Open qry, conn, adOpenStatic
Where-
rs: | Your Declared RecordSet |
qry: | Your SQL Query to be executed to get the Record Set |
conn: | Opened Connection |
adOpenStatic: | Cursor Type |
For Example: Below Code will give the Exact count of all records returned in your RecordSet Object.
Sub Get_Count()
Dim conn As New Connection
Dim rs As New Recordset
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=E:\Student.accdb;" & _
"User Id=admin;Password="
conn.Open (strcon)
qry = "SELECT * FROM students"
rs.Open qry, conn, adOpenStatic
MsgBox (rs.RecordCount)
rs.Close
conn.Close
End Sub
Below are the Cursor Types and it’s description:
Cursor Type | Description |
---|---|
adOpenUnspecified | Does not specify the type of cursor. |
adOpenForwardOnly | Default. Uses a forward-only cursor. Identical to a static cursor, except that you can only scroll forward through records. This improves performance when you need to make only one pass through a Recordset. |
adOpenKeyset | Uses a keyset cursor. Like a dynamic cursor, except that you can’t see records that other users add, although records that other users delete are inaccessible from your Recordset. Data changes by other users are still visible. |
adOpenDynamic | Uses a dynamic cursor. Additions, changes, and deletions by other users are visible, and all types of movement through the Recordset are allowed, except for bookmarks, if the provider doesn’t support them. |
adOpenStatic | Uses a static cursor. A static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible. |
0 Comments