Object variable question

B

Bruce Acciavatti

I need to have a way to identify the individual text and label controls on a
form within my VBA code in order to set the properties depending on
conditions. There are 25 text fields, and I don't want to repeat 25 loops of
code; I want to do it in one nice loop using a counter, stepping through
each control and setting the properties for each.

How do you identify the address to the controls? I've tried declaring as an
object type or control type, but I can't figure out how to store the address
of the particular control in it, so that I can reference it later to change
it's properties. The VB Help is hard to figure on this one.
 
B

Brendan Reynolds

Not sure what you mean by 'address' in this context but perhaps this may
help ...

Dim ctl As Control

For Each ctl In Me.Controls
If ctl.ControlType = acTextBox Then
'Whatever you want to do with all text box controls
If ctl.Name = "MyTextBox" Then
'Things you only want to do with one specific text box
End If
End If
If ctl.ControlType = acLabel Then
'Things you want to do with all labels
If ctl.Name = "MyLabel" Then
'Things you only want to do with one specific label
End If
End If
Next ctl
 
K

Ken Snell [MVP]

Some generic code:

Dim ctl As Control
For Each ctl In Me.Controls
If ctl.ControlType = acTextBox Then
' set value in textbox
ctl.Value = "MyValue"
' set caption of attached label
ctl.Controls.Item(0).Caption = "MyCaption"
End If
Next ctl


Note that another way to do what you seek is to name the textboxes in some
sequential manner (txtValue1, txtValue2, etc.), and then loop through them:

Dim lngLoop As Long
For lngLoop = 1 To 25
' set value in textbox
Me.Controls("txtValue" & lngLoop).Value = "MyValue"
' set caption of attached label
Me.Controls("txtValue" & lngLoop).Controls.Item(0).Caption = "MyCaption"
Next lngLoop
 
B

Bruce Acciavatti

Thanks for the suggestions. I tried the second option, with some changes,
and it works fine.
 
Top