vba sub insert text string into class object refer

2020-02-16 04:06发布

问题:

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