ADO RecordCount Property – RecordSet Object
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 connection to your Database, you can set the appropriate Cursor. Syntax is same as shown in below picture.
rs.Open qry, conn, adOpenStatic
|rs:||Your Declared RecordSet|
|qry:||Your SQL Query to be executed to get the Record Set|
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:
|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.|
My name is Vishwamitra Mishra. Friends Call me Vishwa. This blog is authored by me. I am an Excel Geek. Well, this blog talks a lot about my passion in Excels & Macros so I’ll not talk about it :) I am very much passionate about traveling & quite recently discovered that I am a good photographer too..:P
AND GET A FREE!
E-BOOK FOR EXCEL VBA BEGINNERS
DON'T MISS ANY NEW ARTICLE !
Get your FREE! E-Book & Have Every New Article Delivered Straight To Your Email-Box