Dim buttonName As String
buttonName = columnCellLetter & "14"
I have a command:
Me.ActiveSheet.ButtonB14.ForeColor = &HFF&
but I want to make the 'ButtonB14' part to be dynamic.
Like: Me.ActiveSheet.&buttonName&.ForeColor = &HFF&
How do I do that?
Dim buttonName As String
buttonName = columnCellLetter & "14"
I have a command:
Me.ActiveSheet.ButtonB14.ForeColor = &HFF&
but I want to make the 'ButtonB14' part to be dynamic.
Like: Me.ActiveSheet.&buttonName&.ForeColor = &HFF&
How do I do that?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
First LastPosted May 3, 2023, 11:45 PM
Did not use any error handling. Just tried your first reply.
I get:
Tuhin PaulPosted May 3, 2023, 6:52 PM
The error occurs because the Shape object may not exist or might not have OLEFormat property. In order to handle such cases you need to add some error handling. One way to do this is to wrap the problematic lines in error handler like try catch block. It will display a message box with detailed information about the error if any occur while executing the macro. Another approach could be to check whether the shape object exists before trying to modify its properties.
Tuhin PaulPosted May 3, 2023, 6:51 PM
You can use the Controls collection of the worksheet to access the button control dynamically by its name. check the code below:
In this example, we first create a string variable buttonName which holds the name of the button control we want to modify. Then, we use the OLEObjects property of the worksheet to get a reference to the button control by its name. Finally, we use the Object property of the control to access its properties, such as ForeColor, and modify them as needed.
First LastPosted May 3, 2023, 3:06 PM
I'm using the ActiveX Form button code.
buttonName = columnCellLetter & "14"
Me.ActiveSheet.Shapes(buttonName).OLEFormat.Object.ForeColor = &HFF&
I get:
Here's the ActiveX button:
Here's the line failing:
Rajkiran SwainPosted May 2, 2023, 5:30 AM
To build a string as part of the VBA command syntax, you can use the following code:
Dim buttonName As String
buttonName = columnCellLetter & "14"
Me.ActiveSheet.Shapes(buttonName).OLEFormat.Object.ForeColor = &HFF&
In this code, `Shapes(buttonName)` is used to refer to the button on the worksheet, and `OLEFormat.Object.ForeColor` is used to set the button's foreground color.
Alternatively, if you are using form controls instead of ActiveX controls, you can use the following code:
Dim buttonName As String
buttonName = columnCellLetter & "14"
Me.ActiveSheet.Buttons(buttonName).Font.Color = &HFF&
In this code, `Buttons(buttonName)` is used to refer to the button on the worksheet, and `Font.Color` is used to set the button's foreground color.
Note that the `buttonName` variable should be set to the name of the button you want to reference.