且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用字符串变量来设置VBA中的对象变量? (Excel 2013)

更新时间:2023-02-18 21:08:38

CommandButton属于 OLEObject



尝试

  ButtonString =CommandButton1
设置ButtonObj = ActiveSheet.OLEObjects(ButtonString)

ButtonCaption =Something
ButtonObj.Object.Caption = ButtonCaption要更改的参数类型的示例

请注意,某些属性直接出现在 ButtonObj 下,其他如 cuBmL.pngalt =在此输入图像说明>


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

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