How to loop through all controls on all forms

N

Neil

Hello All,

I am wondering if there is a (quite) simple loop that you could use to loop
through all controls on a form and any subforms that may be on that form and
also any subforms on the subform. I am thinking that i should check the type
of control and see if it is a subform and then call a procedure to check the
subform controls. In this procedure, i should then do the check again and
then call the same procedure (i have no idea how my cpu will behave if i do
this!?). I cant quite get my head round how to do it?

The reason I am doing this is that I want to see if a field exists in a form
or any of it's subforms. My problem arises when a subform has more subforms
on it.

Any suggestions...

TIA,

Neil.
 
K

Kevin McCartney

Use the following code.

Dim ctl1 as control
Dim ctl2 as control
dim frm as form

For each ctl1 in Me.controls
If ctl1.ControlType = acSubform Then
Set frm = ctl1.Name
For each ctl2 in frm.controls
If ctl.ControlType = acSubform Then
Set frm = ctl.Name
ElseIf ctl2.ControlType = acTextBox Then
If ctl2.Name = "The One I Want" Then
msgbox "Found It"
end if
End if
Next ctl2
ElseIf ctl1.ControlType = acTextBox Then
If ctl1.Name = "The One I Want" Then
msgbox "Found It"
end if
End if
Next ctl1

If that not what are after you'll have to loop the the
objects/forms collections, there are many control types so
just press F1 on the highlighted word ControlType within
Access, hope it helps.

regards
KM
 
J

John Vinson

I am wondering if there is a (quite) simple loop that you could use to loop
through all controls on a form and any subforms that may be on that form and
also any subforms on the subform.

A recursive function may be useful here:

Public Sub PollControls(frm as Form)
Dim ctl As Control
For Each ctl In frm.Controls
If ctl.ControlType = acSubform Then
Call PollControls(ctl.Form)
Else
<do what you want with the control>
End If
Next ctl
End Sub
 
N

Neil

Thanks John,

Thats spot on! I knew I had to call the function again but had no idea how
to write it. After several different attempts and failure every time, I
thought I would consult the pros :)

Cheers,

Neil.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top