fatgecko
fatgecko

Reputation: 23

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

I have a number of ActiveX controls/buttons on a page, and I would like to modify several of the parameters of the buttons (in a loop function).

I am fine with writing the loop function to achieve this, but cannot find a way to refer to the object using a string variable. I have set up an object variable (as per below), and a string variable to be used to change the reference for the object variable - but can't find a way to get it to 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

The Set ButtonObj = ButtonString is the command that fails, reporting a Type Mismatch error.

I'm working in Excel 2013.

I really hope there is some way to do this. Any help will be really appreciated!!!

Upvotes: 2

Views: 9007

Answers (1)

brettdj
brettdj

Reputation: 55672

The CommandButton belongs to an 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 under ButtonObj, others such as Caption sit below Object

enter image description here

Upvotes: 3

Related Questions