Search code examples
vbams-accessms-access-forms

How to use Form Controls in Modules


In my modules, I want to use my controls from my form. For example: I want to set focus on a textbox after a certain Sub.

My current solution is to make a subroutine to set all controls in a public variable (see below).

My questions:

  1. What is the best practice? How do people usually do this?
  2. When should I call my subroutine? (is it the first call in the FORM_LOAD sub?)
Public TBnr As TextBox
Public Sub controlsInitieren()
    Set TBnr = Forms("frm_TreeView_Example").pstNr
End Sub

Solution

  • Well, as a general rule, while many platforms seperate out the UI part and the code part? Well, Access is quite much a different approach - it is standard fair to place the required code inside of the form "class" (all forms in Access are a "class", and you can even have muliple instances of the SAME form open more then one time).

    So, in general, your code should be in the forms code (class) module.

    However, you could and call a external routine.

    So in the form, you could call your above routine like this:

    Call MySetFocus(me, "NameOfControlToSetFocusTo")
    

    And your sub would look like this:

    Sub MySetFocus(f as form, sCtrl as string)
    
       f(sCtrl).SetFocus
    
    End Sub
    

    However, as noted, the amount of code above is more code then simply in the forms code module going:

    me.ControlName.SetFocus
    

    However, while the above is a less then ideal example, passing the form "instance" (me) to a external sub or function allows you to referance any property or method or feature that exists in the form in an external routine.

    So in place of say

     me("LastName") = "Zoo"
    

    In the above sample routine, you would and could go;

    f("LastName") = "Zoo"
    

    So any place you would and could use "me" in the form, you can use the form instance you passed from the form. As noted, it is a good idea to use "me", since as I noted, Access does allow multiple copies of the form to be opened at the same time - and thus your code can't distinguish between what form instance you are using unless you pass the current "in context" form. So like in JavaScript, using "this" ?

    In access that current instance of the class object is "me", and you are free to pass that instance to any sub or function you want as per above.