vba sub insert text string into class object reference

≯℡__Kan透↙ 提交于 2019-12-29 09:39:04

问题


I'm pretty new to this, so I'm sorry if I screw up any of the lingo. Thanks a bunch for anybody's help or thoughts.

I have the following wrong code:

Sub ExampleSub(text As String)
  ClassObject." & text & "_attribute = 1
End Sub

So if I call ExampleSub("cheese"), I would like it to set ClassObject.cheese_attribute equal to 1.

Any thoughts? I'm not even sure it's possible.

Thanks so much!


回答1:


Here is another method that might work. Use a scripting dictionary object as one of the classobject's Properties. The Dictionary Object is pretty neat, storing elements in key/value pairs, where the key is a string and the value can be any other type (object, range, Workbook, integer, variant/array, etc.)

So you can use the dictionary object to contain all of these named attributes. In your class module, add code like:

Private pAttributes as Object

Sub Class_Initialize()
    '## Initialize this object to avoid a 91 error
    Set pAttributes = CreateObject("Scripting.Dictionary")
End Sub

Public Property Get Attributes() As Object
    Set Attributes = pAttributes
End Property
Public Property Let Attributes(lAttributes As Object)
    Set pAttributes = lAttributes
End Property

Then, in your code you can simply do:

Sub ExampleSub(text As String)
  ClassObject.Attributes(text) = 1
End Sub

Calling a dictionary key automatically adds the item if it doesn't already exist, but if you wanted more control you could do:

Sub AnotherExample(text as String)
    If ClassObject.Attributes.Exists(text) Then
        MsgBox text & " already exists!", vbInformation
    Else:
        ClassObject.Attributes(text) = 1
    End If
End Sub


来源:https://stackoverflow.com/questions/22874920/vba-sub-insert-text-string-into-class-object-reference

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