The code that's been posted so far is safe, because all you're doing is listing/printing out the names of all controls, and all controls have names. But when you actually start to loop thru controls to do something practical, such as disabling controls, for example, you have to start being a little more careful! Code like this:
Code:
Dim ctl As Control
For Each ctl In Me.Controls
ctl.Enabled = False ' Disable the control
Next ctl
will work without problem, assuming all controls on the form have the Enabled Property! But Labels don't have the Enabled Property, so if you use this code and have a Label on your form, the code will error out!
There's a couple of ways to get around this. One is to tell Access to simply ignore any errors encountered when looping the controls:
Code:
Dim ctl As Control
For Each ctl In Me.Controls
[B]On Error Resume Next[/B]
ctl.Enabled = False ' to Disable
[B]Err.Clear[/B]
Next ctl
There's some difference of opinion as to whether this is good technique or not. But there's another method that can be used in this situation and in situations where you only want to loop thru certain kinds of controls.
Code:
For Each ctl In Me.Controls
If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox Then
ctl.Enabled = False
End If
Next ctl
This will only loop thru Textboxes and Comboboxes, and leave other controls alone.
At other times you may want to be even more select in which controls you loop thru. You may only want to loop thru some textboxes, but not all textboxes. To accomplish this, you'll need to use the Tag Property of the controls. Start by setting the Tag Property of the controls you want to loop thru to some arbitrary word. In this sample we'll use ControlToLoop.
In Design View, select all of the controls you want to loop thru, then goto Properties – Other and in the Tag Property box type in ControlToLoop, without quotation marks. Then use this code, in the appropriate event:
Code:
Dim ctl As Control
For Each ctl In Me.Controls
If ctl.Tag = "ControlToLoop" Then
ctl.Enabled = False
End If
Next ctl
Now only the controls with the tag ControlToLoop will be disabled. To selectively loop thru a different groups of controls, you can assign different tags to different groups and code accordingly.