Looping through controls on a form

kwvh
3StarLounger
Posts: 308
Joined: 24 Feb 2010, 13:41

Looping through controls on a form

Post by kwvh »

Once again I find myself in a predicament of needing something that I read a long time ago, and yet, cannot find the right combinatino of words in the search to find it.

I would like to loop through the controls in a form, and if the control is a text box, I want to either enable or disable it. It was something like

Code: Select all

for each cntrl in controls

User avatar
HansV
Administrator
Posts: 78471
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Looping through controls on a form

Post by HansV »

Try this:

Code: Select all

Dim cntrl As Control
For Each cntrl In Me.Controls
  If cntrl.ControlType = acTextBox Then
    ' code for text boxes goes here
  Else
    ' code for other types of controls goes here
  End If
Next cntrl
See ControlType Property for more info and an extended example.
Best wishes,
Hans

User avatar
HansV
Administrator
Posts: 78471
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Looping through controls on a form

Post by HansV »

BTW, I removed a duplicate of your post.
Best wishes,
Hans

kwvh
3StarLounger
Posts: 308
Joined: 24 Feb 2010, 13:41

Re: Looping through controls on a form

Post by kwvh »

Hans,

Sorry about the duplicate, I didn't know I had duplicated it. Thank you for cleaning up behind me.

Also thanks for the code reference. I canabalized it and came up:

Code: Select all

Sub ToggleFields(OnOff As Boolean)
Dim cntrl As Control

For Each cntrl In Me.Controls
  If cntrl.ControlType = acTextBox Then
    cntrl.Enabled = OnOff
  End If
Next cntrl

End Sub
It lets me enable and disable text boxes on the form depending on specific conditions.

Thanks again!


Ken