Marchese Il Chihuahua
Marchese Il Chihuahua

Reputation: 1139

How to count records and it's numerical value

I am looking for the best way to count records in an underlying table (or query) and allow one to capture that number on the active form. In short, I would like to create an object on my form which tells the users which record out of how many he is currently looking at (e.g. This is record 3 of 6)

I know how to use the record count function but am having difficulty in transfering that number to an object on my form.

Upvotes: 0

Views: 327

Answers (2)

zedfoxus
zedfoxus

Reputation: 37129

On my form I placed a label and called it lblRecords:

On the Form's Current event, Form's CurrentRecord to get the current record number. Although DCount is used below, please read through this article for examples better than DCount to count number of records.

Private Sub Form_Current()
    Me.lblRecords.Caption = "Record " & Me.CurrentRecord & " of " & DCount("ID", "Table1")
End Sub

Using ADODB, a record count can also be obtained.

EDIT

To get recordcount of the datasource bound to the form, one can do this:

Private Sub Form_Current()
    Me.lblRecords.Caption = "Record " & Me.CurrentRecord & " of " & RecordCount()
End Sub


Function RecordCount() As Integer

On Error GoTo ErrorHandler
    Dim RecordsClone As Object
    
    Set RecordsClone = Me.RecordsetClone
    RecordsClone.MoveLast
    RecordCount = RecordsClone.RecordCount
    Exit Function
    
ErrorHandler:
    RecordCount = "NA"
    
End Function

If the form is bound to a query that shows only a small subset of records from a table, Function RecordCount() will show correct information of the number of records.

But what if the data source of the form is changed dynamically using VBA? The above function will still work correctly. Here's an example of how one can change the data source of the form dynamically.

Public Sub ChangeFormQuery()
    Form_Form1.RecordSource = "select * from table1 where [id] between 3 and 4"
    Form_Form1.Requery
    Form_Form1.Refresh
End Sub

Upvotes: 2

Marchese Il Chihuahua
Marchese Il Chihuahua

Reputation: 1139

In alternative to using the DCount function, the following is an optimal solution using the label called 'etcRecordNumber' :

RC = Form_frmStaticDataSkills03.Recordset.RecordCount
RN = Form_frmStaticDataSkills03.CurrentRecord

Me.etcRecordNumber.Caption = "This is record " & RN & " of " & RC

Upvotes: 1

Related Questions