imthatonegirl
imthatonegirl

Reputation: 75

Cycle through user form labels?

I am trying to cycle through the labels in a user form without having 5 lines of code. I know this does not work but I can not think of another way to illustrate what I am looking for.

for i = 0 in 4
     Userform.Lable1+i.caption = "Some Text"
next

Upvotes: 2

Views: 119

Answers (2)

Ricardo A
Ricardo A

Reputation: 1815

Everything you add to a UserForm is in a Control form, and all of them can be accessed by looping UserForm.Controls. By using TypeName(control) it will return the type of Control, such as Label, Text, Combobox, Listbox, Button and more. In this case we want the Label only, so we only check for "Label"

'ctrl Variable for the Loop
Dim ctrl As Control
'Loop all Controls
For Each ctrl In UserForm.Controls
    'Check if the current ctrl is a Label
    If TypeName(ctrl) = "Label" Then
        'This is a label, do your thing yo
    End If
'Check Next Control
Next ctrl

Upvotes: 1

Tim Williams
Tim Williams

Reputation: 166126

The userform's Controls collection can be accessed using a string which is the name of a specific control:

for i = 0 in 4
     Me.Controls("Label_" & i).caption = "Some Text"
next

Upvotes: 0

Related Questions