简体   繁体   中英

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

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).
This ensures that you can eg use a loop that counts from For i = 1 To 10 and automatically adds leading zeros.

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