the Manx Man's MS Access Pages
to subscribe - click here

Looping Through Controls (038)

One part of my user interface style involves enabling and disabling controls on a form. In my early days I did this:

     if something = true then
          me.field1.enable = True
          me.field2.enable = True
          me.field3.enable = True
          me.field4.enable = True

     else
          me.field1.enable = False
          me.field2.enable = False
          me.field3.enable = False
          me.field4.enable = False

     end if

Then I got a bit smarter and did this:

     me.field1.enable = something
     me.field2.enable = something
     me.field3.enable = something
     me.field4.enable = something

That was better, however, what if I needed to flip 30 controls on or off? Too much code. The next step in the process is this:

     dim ctl as control
    
     For Each ctl in me.controls
          if ctl.Tag = "enable" Then ctl.Enabled = something
     Next ctl

Awesome. Now I just modify the tag property of all the appropriate fields (controls) to have the word "enable" and the loop can do hundreds of controls in one fell swoop.

One warning. Make sure the focus of the form is on a control that will not be disabled. An error is caused if you try to disable a control that has the focus. If nothing else, I always have a "Close" command button on every form and that is seldom disabled so a quick me.cmdClose.setfocus will do the trick.

Next.

I want to loop through all the text boxes, or all the labels, or ...

     dim ctl as control
    
     For Each ctl in me.controls
          Select Case ctl.ControlType

               Case acTextBox
                      ... do something with text boxes
               Case acLabel

                      ... do something with labels
               Case acListBox

                      ... do something with list boxes
               Case acComboBox

                      ... do something with combo boxes
               Case acCommandButton

                      ... do something with command buttons
          End Select
     Next ctl

Further Suggestions

For the last example, look up the other types of controls and determine what their constant value is. (example  a text box's constant value is acTextBox)

Next Tip Issue

What's next? Well, maybe I'll get back to the previous series, ... , and maybe not!

 

e-mail the manx man index of tips click here for a laugh profit from the web

tip # 038  ||  previous tip  ||  next tip