PDA

View Full Version : array of controls



ALISTAIRH
04-24-2008, 03:51 AM
I want to loop through a set of controls on an Access form. I've tried the code below but get an error saying that an object has not been defined. It seems thst Me.client refers to the value of the field rather. How can refer to the control object itself? I want to set the 'Enabled' property of the objects. Thanks

ReDim CTRL(6)
CTRL(0) = Me.client
CTRL(1) = Me.system
CTRL(2) = Me.version
CTRL(3) = Me.clientRep
CTRL(4) = Me.fdbeRep
CTRL(5) = Me.testDate
CTRL(6) = Me.session

For i = 1 To 5
CTRL(i).Enabled = False
Next

Oorang
04-24-2008, 08:11 AM
Try:Dim ctrl As Access.Control
For Each ctrl in Me.Detail.Controls
MsgBox ctrl.Name
Next

Note the Form/Page Header/Footer sections have their own control collection. This is just for the controls in "Detail".

ALISTAIRH
04-24-2008, 08:18 AM
Aaron,

Thanks for this but it will loop through every control on the form. I want to loop through 20 specific checkboxes. Therefore I need to build my own collection. In other languages I would just assign control objects to an array.

Oorang
04-24-2008, 10:19 AM
You can dim an array of checkboxes like this:
Private Sub Form_Load()
Dim chkBxs(2) As Access.CheckBox
Set chkBxs(0) = Me.CheckBox1
Set chkBxs(1) = Me.CheckBox2
Set chkBxs(3) = Me.CheckBox3
Dim i As Long
For i = 0 To 2
chkBxs(i).Value = True
Next
End Sub
There are pros and cons to this method. Another way would be to use the Collection type (this example uses textboxes instead):
Private Sub Form_Load()
Dim ctrl As Access.Control
Dim tbxs As Collection
Dim tbx As Variant
Set tbxs = New Collection
For Each ctrl In Me.Detail.Controls
If ctrl.ControlType = acTextBox Then
tbxs.Add ctrl, ctrl.Name
End If
Next
For Each tbx In tbxs
tbx.ForeColor = vbRed
Next
End Sub

DarkSprout
04-25-2008, 03:59 AM
This Should Do The Job!
Dim i As Integer, strCTRL() As String, strControlsList As String
strControlsList = "client;system;version;clientRep;fdbeRep;testDate;session"
strCTRL = Split(strControlsList, ";")
For i = LBound(strCTRL) To UBound(strCTRL)
Me.Controls(strCTRL(i)).Enabled = False
Next