Form Objects in an array?

  • Thread starter Thread starter NateBuckley
  • Start date Start date
N

NateBuckley

Hello I have 10 labels for example sake let us say they are named

lbl1
lbl2
....
lbl9
lbl10

I need to make certain ones vanish on certain conditions and it would be
easier if I could put them into an array, is there a way to make these
objects but as an array? I think it'd be easier and shorter code to treat
them this way in a loop I'm doing.

Thanks for any help in advance!

Nathan
 
Private MyLabels As Collection

Private Sub cmdOK_Click()
MyLabels(1).Visible = False
End Sub

Private Sub UserForm_Activate()
Call Collection_Of_Labels
End Sub

Function Collection_Of_Labels()
Dim Ctrl As MSForms.Control
Dim collLabels As Collection

Set MyLabels = New Collection
For Each Ctrl In Me.Controls
If TypeName(Ctrl) = "Label" Then
MyLabels .Add Ctrl, Ctrl.Name
End If
Next Ctrl

End Function


--
HTH

Bob

(there's no email, no snail mail, but somewhere should be gmail in my addy)
 
Hi Nate,

Perhaps, try something like:

'=========>>
Private Sub UserForm_Initialize()
Dim arr As Variant
Dim i As Long

With Me
arr = VBA.Array(.Label1, _
.Label2, _
.Label3, _
.Label4, _
.Label5, _
.Label6, _
.Label7, _
.Label8, _
.Label9, _
.Label10)
End With

'demo:
For i = LBound(arr) To UBound(arr)
With arr(i)
.Height = 20
.Width = 40
End With
Next i
End Sub
<<=========

However, a better approach for you might
be something like:

'=========>>
Private Sub UserForm_Initialize()
Dim Ctl As Control

For Each Ctl In Me.Controls
If TypeName(Ctl) = "Label" Then
With Ctl
.Height = 20
.Width = 40
End With
End If
Next Ctl

End Sub
<<=========

Alternatively, if you need an array, you
could load the array like so:

'=========>>
Private Sub CommandButton1_Click()
Dim Ctl As Control
Dim arr() As MSForms.Label
Dim i As Long

For Each Ctl In Me.Controls
If TypeName(Ctl) = "Label" Then
With Ctl
i = i + 1
ReDim Preserve arr(1 To i)
Set arr(i) = Ctl
End With
End If
Next Ctl

'Test the array
MsgBox arr(2).Caption

End Sub
<<=========
 

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

Back
Top