Use string variable to set object variable in VBA? (Excel 2013)

I have multiple ActiveX controls / buttons on a page and I would like to change multiple button parameters (in a loop function).

I'm fine with writing a loop function to accomplish this, but can't seem to find a way to reference the object using a string variable. I have set an object variable (as shown below) and a string variable that will be used to change the reference for the object variable, but cannot find a way to make it work.

This is the code that does NOT work:

Private Sub TrialCode_Click()

Dim ButtonObj As Object
Dim ButtonCaption As String
Dim ButtonString As String

ButtonString = "CommandButton1"
Set ButtonObj = ButtonString

ButtonCaption = "Something"

ButtonObj.Caption = ButtonCaption  'example of the kind of parameters I want to change

End Sub

      

Set ButtonObj = ButtonString

is the command that fails, reporting a type mismatch error.

I am working in Excel 2013.

I really hope there is a way to do this. Any help would be really appreciated.

+2


source to share


1 answer


CommandButton belongs to OLEObject

try

ButtonString = "CommandButton1"
Set ButtonObj = ActiveSheet.OLEObjects(ButtonString)

ButtonCaption = "Something"
ButtonObj.Object.Caption = ButtonCaption  'example of the kind of parameters I want to change

      



Note that some properties occur directly below ButtonObj

, others like Caption sit below Object

enter image description here

+2


source







All Articles