如何以 VBA 形式动态更新标签标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20677449/
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
How to dynamically update labels captions in VBA form?
提问by Takedasama
I want to dynamically set the caption for an array of labels (within a VBA form) based on values stored in a worksheet. Thus far I can set them one-by-one like this:
我想根据存储在工作表中的值动态设置标签数组(在 VBA 表单中)的标题。到目前为止,我可以像这样一一设置它们:
Label1.Caption = MySheet.Range("A1").Value
Label2.Caption = MySheet.Range("B1").Value
Label3.Caption = MySheet.Range("C1").Value ...
Having lots of labels that follow a recurrent pattern, I want to use something smarter, like:
有很多遵循重复模式的标签,我想使用更智能的东西,例如:
'Method1
For i = 1 To X
Dim MyLabel as Object: Set MyLabel = "Label" & i
MyLabel.Caption = MySheet.Cells(i + 1, i).Value
Next i
'Method2
For i = 1 To X
Label(i).Caption = MySheet.Cells(i + 1, i).Value
Next I
'Both Methods failed. I really appreciate some feedback on this.
回答by Siddharth Rout
Use Controls
object
使用Controls
对象
For i = 1 To X
Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
回答by Ahmet Toka
If you want to use this in VBA:
如果你想在 VBA 中使用它:
For i = 1 To X
UserForm1.Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next