Microsoft Access VBA Tutorials for self-paced learning, Class Modules, SQL Techniques, and AI Integration Guides.

Overlaying Sub-Forms in Real-Time

Overlaying Subforms in Real-Time.

This session is about loading two or more Forms into a single Subform control interchangeably. Normally, we place only one Form in a Subform Control during design time. A main Form can host one or more Subforms, typically linked through the Link Master Fields and Link Child Fields properties.

Remember this: a Subform control is essentially a Container that holds a Form object reference in its Source Object property. If you clear the form name from this property, the container remains empty on the main form. By changing the Source Object value at runtime, you can load any Form you want into the same subform control. This is the key to dynamically switching multiple Forms.

Let us look at a quick example of loading three different forms into a single Subform control, one after the other, replacing the previously loaded Form. Check the video below for a demonstration:

You can create this Form very easily. See the sample image given below:


Sample Form Design.

  1. You can either use an existing form with enough space below the data fields or create a blank Form in Design View. In both cases, you can drag another form from the Navigation Pane and drop it onto the Detail Section. This action creates a Subform Container Control and places the dragged Form inside it as a subform. If you choose to create a new blank Form, leave enough space above the subform to add an Option Group Control later.

  2. Display the Property Sheet (F4) of the subform while the subform container is in the selected state, and change the Name Property value to subFrm. 

  3. Change the Child Label Name Property Value to HeaderLabel.

  4. Create an Option Group Control above the subform, with the names of any three Forms as Labels.

  5. Change the Options Group Control Name Property value to Frame1.

  6. Change the Options Group Control's Default Value property value to 0.

  7. Select the After Update Event property, select [Event Procedure] from the drop-down list, and click the Build (...) button to open the VBA Editing window.

  8. Copy and paste the following VBA Code into the Module, overwriting the Private Sub Frame1_AfterUpdate() ... End Sub lines:

    Frame1_AfterUpdate() Event Procedure.

    Private Sub Frame1_AfterUpdate()
    Dim i, sub_Form As SubForm
    
    Set sub_Form = Me.subfrm
    i = Me![Frame1]
    Select Case i
        Case 1
          sub_Form.SourceObject = "frm_Session"
          Me.headerLabel.Caption = "frm_Session:"
        Case 2
          sub_Form.SourceObject = "frm_Payments"
          Me.headerLabel.Caption = "frm_Payments:"
        Case 3
          sub_Form.SourceObject = "Stationary"
          Me.headerLabel.Caption = "Stationary:"
    End Select
    
    End Sub
  9. Modify the above Code to replace the Form Names in quotes with your own Form names.

  10. Press ALT+Q to close the VBA Window.

  11. Change the Option Group control's Child-label Caption to Form Selection.

  12. Save and close the Form.

  13. Open the Form in Normal view and try out the Option Group Radio buttons to load your forms into the subform control, in any order you like.

When Two Sub-Forms Are Linked Together.

Assume you have a Main Form (e.g., Students) that contains two subforms: frm_Session and frm_Payments. The first subform (frm_Session) links to the Main Form Students through a common field, StudentID—though that's not the key point here.

The second subform (frm_Payments) is not linked directly to the main form. Instead, it is linked to the first subform (frm_Session) via the SessionID field. To ensure the second subform displays only the related records, you must configure its Link Master Fields and Link Child Fields properties. The critical detail is that the Master Field reference must come from the first subform control, not the main form. This is the main challenge in setting up this type of subform relationship.

The image of the sample form is given below:

View the Demo Video of two subforms in action.

The limitation of the Link Master Fields property of a subform control is that it can only be set to reference field or control names at design time. It does not accept expressions or fully qualified references, and it always expects those references to come from the main form,

The simplest solution is to create an unbound TextBox on the main form and set its Control Source to an expression such as:

=[frm_Session].[Form]![SessionID]

This allows the TextBox to display the current record key value from the first subform. You can use the TextBox name as the Link Master Field for the second subform. To keep the form uncluttered, set the TextBox’s Visible property to No.

With this setup, the second subform will correctly filter its data based on the SessionID from the first subform. If you load any form that doesn't have the SessionID field in the second subform control, Microsoft Access will prompt for the field value set in the Link Child Fields property.

The VBA Code.

The VBA Routines that run on the CommandButtons Stationary and Payments Click Event Procedures are given below:

Stationary Command Button Click event procedure:

Private Sub cmdStationary_Click()
Dim frm As SubForm
Set frm = Me![frm_Payments]

With frm
    'load Stationary Form into the control
    .SourceObject = "Stationary"
    .Requery
End With
  'second Sub-Form Child Label Caption Change
  Me.Label7.Caption = "Stationary"
  'Enable Payments Command Button
  Me.cmdPayments.Enabled = True
  'Shift the Focus to cmdPayments command button
  Me.cmdPayments.SetFocus
  'Disable cmdStationary command Button
  Me.cmdStationary.Enabled = False
  Me.Refresh
  
End Sub

Payments Command Button Click event procedure:

Private Sub cmdPayments_Click()
Dim frm As SubForm
Set frm = Me![frm_Payments]
With frm
    .SourceObject = "frm_payments"
    .Requery
End With
'Change Header Label Caption
Me.Label7.Caption = "frm_payments"
'Enable Stationary Command Button
Me.cmdStationary.Enabled = True
'Change focus from cmdPayments
'in preparation to disable the Command Button
Me.cmdStationary.SetFocus
'Disable cmdPayments Command Button
Me.cmdPayments.Enabled = False
Me.Refresh

End Sub

Download the Demo Database.

You may download the sample databases for a quick view of this trick.


Download Demo SubFormTrick2007.zip

Download Demo SubFormTrick2003.zip

Share:

2 comments:

  1. The image of the sample form talks of a text box with the expression:=[frm_Session].[Form]![SessionID] but I don't see such text box when I open subFormsTrick2007.accdb in design view.

    ReplyDelete
  2. Sorry, scrap my previous message, I see it now in the Students form :-)

    ReplyDelete

Comments subject to moderation before publishing.

Listen to this article
Ready to read.

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet External Links Queries Array Class Module msaccess reports Accesstips msaccess tips WithEvents Downloads Objects Menus and Toolbars MsaccessLinks Process Controls Art Work Collection Object Property msaccess How Tos Combo Boxes ListView Control Query VBA msaccessQuery Calculation Dictionary Object Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes Recordset Top Values Variables msaccess email progressmeter Access2007 Copy Excel Expression Fields Join Methods Microsoft Numbering System RaiseEvent Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup Wrapper Classes database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler Export External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code