Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Wednesday, January 9, 2013

Setting Focus on a field inside a Sub-Form

Introduction.

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 on the main form.  The Sub-Form has other controls (like Textboxes) within it 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 in the Amount field of frm_Payments directly, when frm_Payments doesn't have the focus on, through VBA is not possible.

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 change to that field.

But, we can retrieve the value directly from the Amount field of frm_Payments, even when the focus is not ON 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 ON 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 two-step action to address a control within a sub-form to set focus on:

  1. Set focus on the sub-form container first.  Setting the Tab Index Value of the frm_Payment to 0 also works.
  2. 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:

Me.Payments.form.SetFocus
Me.Payments.form.Amount.SetFocus

The following version of the above statements is also valid:

Forms![frm_Students]![frm_Payments].SetFocus
Forms![frm_Students]![frm_Payments].Form.Amount.SetFocus

What Next...

Next, we will see how to jump from the last field of one sub-form record to its corresponding record field on the second sub-form directly.  If you think it is so easy after learning the above two lines, then think twice.

No comments:

Post a Comment

Comments subject to moderation before publishing.

Powered by Blogger.