Using a for loop to call consecutive variable name

2019-07-25 11:56发布

Scenario) I have seven variables; labelKid1, labelKid2, ...LabelKid3. I'm searching through cells to find ones that are not empty, and then entering the value into the label, starting with labelKid1, and then moving on to the next label.

Question) Is there a way to us a for loop to go through these variables? By this I mean can I somehow call the variable with something such as labelKid + j , with j being the value of the for loop? This would allow me to march through the labels a lot more easily.

Now, I understand that I could probably do this by putting the labels into an array and using a for loop to call their indicies, but is there a way to do it as I stated above?

2条回答
狗以群分
2楼-- · 2019-07-25 12:41

You can achieve this using UserForm1.Controls("labelKid" & i) Which calls any form control by name associated with UserForm1

So you would need something like this

Sub ControlName()
Dim i As Long
For i = 1 To 10
    UserForm1.Controls("labelKid" & i).Value = i 
Next
End Sub

Hope this helps!

查看更多
Juvenile、少年°
3楼-- · 2019-07-25 12:47

No, VBA does not support variable variables (as they are called in PHP). As you said you will need to use a list, dictionary or similar instead.

查看更多
登录 后发表回答