Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a variable to set a userform object name

I am working on a specific project where I need to loop through a set of user form objects and do something to each of them (in the case it’s a label). I have them named lbl1, lbl2, lbl3, … so on and so forth. I need to find a way to loop through and toggle the visibility of them with my loop.

I have tried the following to no avail:

(This is an incomplete portion of the code only using the relevant information)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Dim i as Long
Dim result as Object

'… ‘code to define what i is

Set result = “lbl & i 
'… ‘ more code to continue the loop

>Solution :

You can utilize Controls collection. Give a try-

Private Sub CommandButton1_Click()
Dim i As Long

    For i = 1 To 3
        Me.Controls("lbl" & i).Visible = False
    Next

End Sub

You can also use Set method. Then it would be like-

Private Sub CommandButton1_Click()
Dim i As Long
Dim lb As Object

    For i = 1 To 3
        'Me.Controls("lbl" & i).Visible = False
        Set lb = Controls("lbl" & i)
        lb.Visible = False
    Next

End Sub

You can also declare variable as Control like Dim lb As Control.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading