简体   繁体   中英

Having trouble using For/Next with variables

I am using an excel Userform and on the form I have created several label fields that are named in sequential order. For example: Label1, Label2...LabelX I want to assign the .caption for them from an array that I have built separately. Using a For/Next loop makes the most sense in my head, but since it is a label, I am having trouble. I cannot even get the code to take in a way that makes sense. Below is what I was trying...

For i = 1 To 100
    Labeli.Caption = Array(i)
Next i

If there is a way to keep it inside of the loop, it would make the code a lot less cumbersome. Thank you in advance for your assistance.

Try this:

i = 1

For Each itm In Me.Controls

    If itm.Name = "Label" & i Then
        itm.Caption = Array(i)
        i = i + 1
    End If

Next

You cannot form an Object Name like Labeli where i is a Variable. But you can loop through all the controls and check if that Label have a Name like Label1 and so on.


Another Method:

For i = 1 To 100
        Me.Controls("Label" & i).Caption = Array(i)
Next

What you can to is "build" the name of the Labels like this:

Userform.Controls("Label" & i).Caption

Userform is a Reference to the Userform, if you write it the codebehind of the Userform you can use Me.

But if you have a hundred Labels, there may be better ways to create your Userform, this looks a bit like a XY-Problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM