vba 使用for循环在VBA中调用连续的变量名(即car1、car2....car10)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11622648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a for loop to call consecutive variable names (ie car1, car2.... car10) in VBA
提问by nobillygreen
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.
场景)我有七个变量;labelKid1、labelKid2、...LabelKid3。我正在搜索单元格以查找非空单元格,然后将值输入到标签中,从 labelKid1 开始,然后移至下一个标签。
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.
问题)有没有办法让我们使用 for 循环来遍历这些变量?我的意思是我可以以某种方式调用诸如 labelKid + j 之类的变量,j 是 for 循环的值吗?这将使我能够更轻松地浏览标签。
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?
现在,我知道我可以通过将标签放入数组并使用 for 循环来调用它们的索引来做到这一点,但是有没有办法像我上面所说的那样做到这一点?
回答by verdesmarald
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.
不,VBA 不支持可变变量(因为它们在 PHP 中被调用)。正如你所说,你需要使用列表、字典或类似的东西。
回答by Scott
You can achieve this using UserForm1.Controls("labelKid" & i)
Which calls any form control by name associated with UserForm1
您可以使用UserForm1.Controls("labelKid" & i)
which 通过与 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!
希望这可以帮助!