简体   繁体   English

按对象名称动态访问对象属性

[英]Dynamically access object properties by object name

I have several text boxes that I want to cycle through and set their text value whenever the user clicks a button, one box every click.我有几个文本框,我想在用户单击按钮时循环并设置它们的文本值,每次单击一个框。

They are all named the same with a number added to the end它们都以相同的名称命名,并在末尾添加一个数字

Light_Number_01
Light_Number_02
Light_Number_03
Light_Manufacturer_01
Light_Manufacturer_02
Light_Manufacturer_03

I want to set all text boxes with the same numerical ending with the same click, my current thought process was to do something like this我想用相同的点击设置所有具有相同数字结尾的文本框,我目前的思考过程是做这样的事情

Light_Pointer = 01
Light_Number_Pointer = "Light_Number_" & Light_Pointer
Light_Manufacturer_Pointer = "Light_Manufacturer_" & Light_Pointer
Light_Number_Pointer.Text = 'Logic from other parts of the program
Light_Manufacturer_Pointer.Text = 'Logic from other parts of the program

I was hoping to be able to do something like that, that is to access the text boxes by their name,我希望能够做这样的事情,那就是通过他们的名字访问文本框,

I'm hoping to keep this as simple as possible since this is likely to be maintained by even lower experience programmers than myself in the future, but I'm willing to consider more complicated solutions if this doesn't work我希望尽可能保持简单,因为这可能会由比我自己经验更低的程序员在未来维护,但如果这不起作用,我愿意考虑更复杂的解决方案

You can use Controls() to access a control by its name您可以使用Controls()通过名称访问控件

Dim i As Long
i = 2
MyForm.Controls("Light_Number_" & Format$(i, "00")).Text = ""         'same like MyForm.Light_Number_02.Text
MyForm.Controls("Light_Manufacturer_" & Format$(i, "00")).Text = ""   'same like MyForm.Light_Manufacturer_02.Text

Note that Format$(i, "00") ensures that i is always converted into a 2 digit number with leading zero (if i is smaller than 10).请注意, Format$(i, "00")确保i始终转换为带有前导零的 2 位数字(如果i小于 10)。
This ensures that you can eg use a loop that counts from For i = 1 To 10 and automatically adds leading zeros.这确保您可以使用例如从For i = 1 To 10计数并自动添加前导零的循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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