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

∥☆過路亽.° 提交于 2019-12-08 03:06:33

问题


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!!!


回答1:


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



来源:https://stackoverflow.com/questions/27614692/use-string-variable-to-set-object-variable-in-vba-excel-2013

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!