VBA use CommandButton.name as a string for Range()

lightmaster

New Member
Joined
Feb 7, 2018
Messages
13
I've got a UserForm with hundreds of small Command Buttons on them that are all named as as either Predicted followed by some numbers or Actual followed by some numbers. I've also got an equal number of cells in the spreadsheet that are named the same as all those Command Buttons. What I'm trying to do is, when the UserForm is initialized, loop through all the Command Buttons and set their caption to the value of the corresponding spreadsheet cell. Using this code, I can both print the names of all the Command Buttons, and set all the captions to the value of that Named Range, but if I replace "Predicted418" with ctrl.Name, I get a "Run-time error '1004'" error. I figure the issue is that ctrl.Name must not be a string, and Range() requires a string, but I can't figure out how to get ctrl.Name to be a string.

Code:
    Dim ctrl As Control
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "CommandButton" Then
            Debug.Print ctrl.Name
            ctrl.Caption = Sheets("Execution Test Entry").Range("Predicted418").Value
        End If
    Next ctrl
 

Excel Facts

Control Word Wrap
Press Alt+Enter to move to a new row in a cell. Lets you control where the words wrap.
Ctrl.Name is a string. If you get an error with:

Code:
ctrl.Caption = Sheets("Execution Test Entry").Range(ctrl.Name).Value

you must have at least one button whose name doesn't match a named range.
 
Upvote 0
Soon as I read that, I knew exactly which buttons it was tripping up on. Added
Code:
And ctrl.Name <> "SaveButton"
and it immediately worked right off the bat. Guess I got so hung up on whether or not ctrl.Name was a string that I didn't even think about other buttons that aren't ranges.

Thanks!
 
Upvote 0

Forum statistics

Threads
1,223,227
Messages
6,170,849
Members
452,361
Latest member
d3ad3y3

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top