For Each Control - identify control by name?

CBrighton

Surfing while working...
Local time
Today, 00:06
Joined
Nov 9, 2010
Messages
1,012
I have a piece of code which uses For Each Control to loop through a piece of code for each control on my form.

However, I want to be able to limit it to certain controls on the form now.

Worst comes to worst I'll stick the code in a module and pass the control name to the function but I'd rather do this without having to do major work on the code.

I had been trying code like this but it looks like .ControlName doesn't do what I had hopes when used on a control object (which is what ctl is in the following code):

Code:
Dim ctl as Control
For Each ctl in Me.Controls
   If ctl.ControlName = "NameOFirstControlToWork" or ctl.ControlName = "NameOfSecondControlToWork" Then
      'Code to run
   End If
Next Ctl


Anyone have any suggestions? This is access 97 by the way (don't even start about how outdated that is... not my decision).
 
Do you get an error message? Does the code not work?
 
No error message.

It does go into the If statement, so it decides that the criteria for the If statement has been met.

I tried adding "msgbox ctl.ControlName" into the process which is not included here, expecting to get as many message boxes as I have control names in the If statement. However the messagebox line of code seems to be skipped.

Simple code to test would be:

Code:
Dim ctl as Control
For Each ctl in Me.Controls
   msgbox ctl.ControlName
Next ctl

As far as I can tell nothing happens when I run that code, certainly no messageboxes are displayed (I'd expect 1 messagebox for each control on the form, each displaying the name of the control which is currently assigned to ctl).
 
I don’t suppose you have something like this lying around in your project:-

Code:
Public Sub msgbox(x)


End Sub

:D
 
Try this modified version

Code:
Dim ctl As Control
For Each ctl In Me.Controls
   MsgBox ctl.name   [COLOR="Lime"]'ControlName[/COLOR]
Next ctl
End Sub
 
.Name worked perfectly, thanks.

After getting home yesterday I realised I had working code within my audit trail function in another database so had this not worked I would have checked that and posted the solution.
 
Is there a way to make all controls visible using this technique?

Oops, it was not on the drop down list, but if you type it in...it works!

Code:
Dim ctl As Control

For Each ctl In Me.Controls
ctl.Visible = True

Next
 
Last edited:

Users who are viewing this thread

Back
Top Bottom