Power Tip: Count the number of rows in a subform

Today's guest blogger is Access MVP Garry Robinson, who offers the Smart Access collection of articles at http://www.vb123.com/kb.

Here's a great tip from the Smart Access collection that I used recently. I needed the count of rows in a subform to display on the main form. It's surprisingly easy--all you need to do is assign the RecordCount property for a subform's recordset to the TextBox on the main form. There's no need to loop through the rows in a recordset for a subform.

First, the procedure assigns a reference to the Subform control (Child20) for the subform. Then, the procedure uses the control's Form property to return the subform's recordset, which, in turn, allows me to access the RecordCount property value. The procedure assigns the value to txtOrderCount, which is on the main form. Putting this code in the Form_Current() event for the main form causes the text box to update each time I move to a new record.

Private Sub Form_Current()

    'Declare a control variable
    Dim ctl1 As Access.Control

    'Point at subform control
    Set ctl1 = Me.Child20

    'Get record count
    Me.txtOrderCount = ctl1.Form.Recordset.RecordCount

    Set ctl1 = Nothing

End Sub

The complete tip has a lot more information about accessing subforms—see it here: www.vb123.com/kb/200402_rd_sub.htm

Enjoy!
Garry

Send your Power Tips to Mike & Chris at accpower@microsoft.com, and learn more about Access at http://office.com and http://msdn.microsoft.com.

Office Blogs Comments

Comments: (4) Collapse

  • Is nice to see other implementations of the same code, i have been using this Form.Recordset.RecordCount since very long .. . i remember using in the textbox itself. Me.txtOrderCount = subChild.Form.Recordset.RecordCount Edwin

  • Good tip, Garry.

    I use the shorter version of this technique - similar to Edwin:

    Private Sub Form_Current() Me.txtOrderCount = Me.Controls("SubForm Name").Form.Recordset.RecordCount

    End Sub Cheers, Nadia

  • Excellent tip. You could also do it with a DCOUNT. Let's say you've got Orders and OrderDetails with an OrderID field that's common to both forms: =DCOUNT("*","OrderDetails","OrderID=" & OrderID) I tend to find myself using the domain aggregate functions (DLOOKUP, DCOUNT, DSUM, etc.) a lot. :)

  • Often when I create databases for others I am specifically or contractually asked to NOT use any code in the database. So I agree with Richard's comment and use the database functions instead of writing code. And if you are wondering why I am asked that, I've had clients tell me that they don't want to have to pay to have me come back for every little customization, which they believe would happen if I packed a lot of code in the database.

Comments

Comments: (loading) Collapse