Setting Focus on a field in a Sub-Form.
The Main Form (frm_Students) has two Sub-Forms (frm_Sessions and frm_Payment). A sample image of such a Form is given below:
Sub-Form Container and Sub-Form.
Each Sub-Form on the main form is placed within a Sub-Form Container. The Sub-Form contains other controls (like Textboxes), and we cannot set focus directly on any of these controls from outside the sub-form container. That doesn’t mean that we cannot address the controls directly to retrieve or set the value into that control through VBA.
The Difference Between Setting Focus and Retrieving Values
Setting focus directly in the Amount field of frm_Payments subform from the Main Form using code doesn't work.
Example:
'this statement will not work when frm_Payments doesn't have focus Forms![frm_Students]![frm_Payments].Form.Amount.SetFocus
The above statement may highlight the Amount field, but the focus will not be set on that field.
But we can retrieve the value directly from the Amount field of frm_Payments, even when the focus is not on that form, with the following statement.
Example-2:
'this statement retrieves the Amount field value directly. m_Amt = Forms![frm_Students]![frm_Payments].Form!Amount
When the frm_Payments sub-form has the focus, you can address a control (say the Amount field) within that form to set the real focus on it.
It simply means that it takes a two-step action to address a control within a sub-form to set focus on:
- Set focus on the sub-form container first. Setting the Tab Index Value of the frm_Payments to 0 also works.
- Set focus on any control within the frm_Payments sub-form.
So, it is a two-step process, and the following two VBA statements do the job:
With Me.Payments.form .SetFocus .Amount.SetFocus End With
The following version of the above statements is also valid:
With Forms.[frm_Students].[frm_Payments] .SetFocus .Form.Amount.SetFocus End With
What Next...
Next, we will see how to jump from the last field of one subform record to its corresponding record-field on the second subform. If you think it is so easy after learning the earlier lines of code, then try it yourself and come back to the next episode.










No comments:
Post a Comment
Comments subject to moderation before publishing.