Enabling All Controls on a Form With a Loop

Also, How to Use "Tags" For Enabling a Specified Group of Controls

March 2002
Go to Tags Section
home

One scenario that got me stuck on this day was a scenario whereby all the text boxes (and combo boxes) on a form were NOT enabled by default. I wanted a quick way to 'enable' them without having to enter a separate statement for every single one.

A very nice gentlemen in the newgroups provided me with the code, which I had to modify only slightly (so as to enable the combo boxes as well). It follows:


' The Dim cntrol as Control line seems unnecessary
' but I've included it since it was suggested to me
Dim cntrl As Control
For Each cntrl In Me.Controls
   If cntrl.ControlType = acTextBox Or cntrl.ControlType = acComboBox Then
       cntrl.Enabled = True
   End If
Next cntrl

I also received this code as a suggestion, included here for reference:


Dim ctl As Control
For Each ctl In Me.Controls
If ctl.ControlType = acTextBox Then
'Toggle off or on depending on current state.
ctl.Enabled = Not ctl.Enabled = True
'If you want to just enable then use this:
'ctl.Enabled = True
End If
Next
End Sub

Using Tags to Enable a Specified Group of Controls

In forms, you can set a "Tag" property to a text box or any other control, and that way easily execute commands to a specified group of controls in a form. That way you don't have to have 25 different commands for each control--say, having to do "Me.StartDate.Enabled=False" and then "Me.txtDate.Enabled=False" over and over 25 times for each one. It's a great time saver.

If you want a certain group of controls on a form to be enabled or disenabled all at once, do this:

  • Enter the following code in a module:
    
    Function EnableDisableControls(frm As Form, fEnabled As Boolean)
        ' Enable or disable all controls on form {frm} that have
        ' their Tag properties set to "Enable/Disable", according
        ' to the value passed as {fEnabled}.
    Dim ctl As Control
    For Each ctl In frm.Controls
        If ctl.tag = "Enable/Disable" Then
            ctl.Enabled = fEnabled
        End If
    Next ctl
    End Function
    
    
  • With the form open under DESIGN view, select the relevant text box's properties
  • Under "Other...Tag" enter the tag name you want (in this case, we will use Enable/Disable) Don't use quotes
  • Then in your form use the following command to have the controls disabled or enabled in your form

    Disabled:
    Call EnableDisableControls(Me, False)
    
    
    Enabled:
    Call EnableDisableControls(Me, True)
    
    
    (Note: if Me in the parenthesis doesn't work, try substituting Screen.ActiveForm)