vba sub插入文本字符串到类对象引用 [英] vba sub insert text string into class object reference

查看:291
本文介绍了vba sub插入文本字符串到类对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新鲜,所以很抱歉,如果我搞砸了任何隐语。感谢一个人为任何人的帮助或想法。



我有以下错误的代码:

 code> Sub ExampleSub(text As String)
ClassObject。& text&_attribute = 1
End Sub

所以如果我调用ExampleSub(cheese),我想让它设置ClassObject.cheese_attribute等于1。



任何想法?

解决方案

这里是另一种可能工作的方法。使用脚本字典对象作为类对象的属性之一。 字典对象非常整齐,在键/值对中存储元素,其中键是字符串并且该值可以是任何其他类型(对象,范围,工作簿,整数,变体/数组等)



因此,您可以使用字典对象包含所有这些命名的属性。在类模块中,添加如下代码:

 私有pAttributes作为对象

Sub Class_Initialize b $ b'##初始化此对象以避免91错误
设置pAttributes = CreateObject(Scripting.Dictionary)
结束子

公共属性获取属性Object
设置属性= pAttributes
结束属性
公共属性让属性(lAttributes As Object)
设置pAttributes = lAttributes
结束属性



然后,在您的代码中,您可以直接执行:

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

调用字典键会自动添加项目,如果它不存在,但如果你想要更多的控制,你可以做:

  Sub AnotherExample(text as String)
如果ClassObject.Attributes.Exists(text)then
MsgBox text& 已存在!,vbInformation
否则:
ClassObject.Attributes(text)= 1
如果
结束End Sub
pre>

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!

解决方案

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

这篇关于vba sub插入文本字符串到类对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆