Looping Through Subforms on Form

AbbottF

Registered User.
Local time
Today, 15:43
Joined
Jan 22, 2013
Messages
25
I have multiple copies of a subA on a form. Each one has a unique name subAA, subAB, .... I am trying to populate text fields on each form based on the contents of a class. I can find the subforms in the controls collection but I can't figure out how to reference the text boxes on each form.

Any suggestions?

Also, if there's a smarter way to get the control using its name, that would also be better than looping through all of them.

Code:
Private Sub DisplaySummary(subFormName As String, totals As clsTotals)
    Dim subControl As Control
    For Each subControl In Me.Controls
        If subControl.name = subFormName Then Exit For
    Next subControl
    
    If subControl.name = subFormName Then
        subControl!Form!lblTotals = totals.MyTitle
        subControl.Form.txt12Month = totals.MoneyTrailing12
        subControl.Form.txtLastYear = totals.MoneyLastYear
        subControl.Form.txtPriorYear = totals.MoneyPriorYear
        subControl.Form.txtYTD = totals.MoneyYTD
    End If
End Sub
 
If you already know the name of the subform control, you can just use that as the index in the controls collection and you don't need a loop. Here's code ...
Code:
Private Sub DisplaySummary(subFormName As String, totals As clsTotals)
    With Me.Controls(subFormName).Form
        !lblTotals = totals.MyTitle
        .txt12Month = totals.MoneyTrailing12
        .txtLastYear = totals.MoneyLastYear
        .txtPriorYear = totals.MoneyPriorYear
        .txtYTD = totals.MoneyYTD
    End With
End Sub
See what's going on there? Controls in the Controls collection are indexed by name, so you can reference a member of that collection by name, and the child control contains a Form, so you get "Me.Controls(subFormName).Form" as a one-stop-shop reference to the form in the named control.
 

Users who are viewing this thread

Back
Top Bottom