Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA how do I build reference to a userform object property from a string?

I have a button on my userform, lets call it CommandButton2. I have code that outputs at the very end a long value of 2 to refer directly to the button lets call that long ButtonValue.

Now if I wanted to loop through a number of buttons using the long value my first thought would be to do something like CommandButton(ButtonValue).Caption = Value, which obviously doesn’t work.

I can use something like string concatenation to produce a string output CommandButton2.Caption but then how do I actually get that string to reference the UserForm object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I even able to do such a thing and still make use of the .Caption object property? Any help would be appreciated.

>Solution :

Following should work for you. Use Controls collection to set property of an object from variable.

Private Sub CommandButton1_Click()
Dim ButtonValue As Long
    ButtonValue = 2
    Controls("CommandButton" & ButtonValue).Caption = ButtonValue
End Sub
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading