使用字符串变量在 VBA 中设置对象变量?(Excel 2013)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27614692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use string variable to set object variable in VBA? (Excel 2013)
提问by fatgecko
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).
我在一个页面上有许多 ActiveX 控件/按钮,我想修改按钮的几个参数(在循环功能中)。
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 NOTwork:
这是它的代码不工作:
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 Mismatcherror.
这Set ButtonObj = ButtonString
是失败的命令,报告类型不匹配错误。
I'm working in Excel 2013.
我在 Excel 2013 中工作。
I really hope there is some way to do this. Any help will be really appreciated!!!
我真的希望有办法做到这一点。任何帮助将不胜感激!!!
采纳答案by brettdj
The CommandButton belongs to an OLEObject
命令按钮属于 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 Captionsit below Object
请注意,某些属性直接出现在 之下ButtonObj
,其他属性(例如Caption)位于Object之下