Loop through objects on a form

Gary Samuels
Gary Samuels used Ask the Experts™
on
I have a form which contains about 30 checkboxes. It contains a button to uncheck all boxes. The button_click event walks through each checkbox and sets it value to zero.

Is there a way to loop through all the checkboxes on the form instead of dealing with each object one at a time?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2010
Commented:
Assuming all the checkboxes have names starting with "chk" or similar...


Dim ctrl As Object

For Each ctrl In Me.Controls
    If ctrl.Name Like "chk*" Then ctrl.Value = False
Next

Open in new window

Dale FyeOwner, Dev-Soln LLC
Most Valuable Expert 2014
Top Expert 2010

Commented:
No points please, just another alternative, since many developers don't use a standard naming convention.

ctrl.controltype = acCheckBox then ctrl.Value = false

If you don't mind my asking, why do you need 30+ checkboxes on a single form?  This is pretty rare in a well normalized database application.
Top Expert 2016

Commented:
this will uncheck all check boxes regardless of what ever the name is


dim ctl as control

for each ctl in me.controls
    if ctl.controltype=accheckbox then
      ctl.value=0
   end if
 
next

Open in new window

Gary SamuelsPlant Manager

Author

Commented:
Thanks
Gary SamuelsPlant Manager

Author

Commented:
It's part of a search feature. Each box represents a field on a different form. The user can select which field or fields they would like to search. I do have another question and I will post it as a new question if I need to.


I also have a global variable that I would like to set to the same value as the checkbox. While the checkbox is named "chkPurchaser" the global variable is named "gPurchaser".

In the same loop I was thinking about using Replace(ctrl.Name,"chk","g") and then setting the global variable to the same value. Is this possible?

Or can you create a global checkbox? Define the checkbox in Module1 and then give a checkbox on a form the same name, making the value global?
Dale FyeOwner, Dev-Soln LLC
Most Valuable Expert 2014
Top Expert 2010

Commented:
The global variable question should be posted as a separate question.

You might want to consider using a multi-select listbox rather than checkboxes.  The listbox has a Fieldlist property which would populate it with all of the field names from whatever table or query you provide as the data source.  It would also take up a lot less screen realestate than the checkboxes and their associated labels.

This way, if the fields change, you don't have to redesign your form.  There are other issues associates with a multi-select list, but these are generally very easy to handle.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial