列出VBA 2003中的类的属性 [英] List the properties of a class in VBA 2003
问题描述
我到处搜索,看是否有一个简单的答案,但是似乎没有...
I've searched all over to see if there is an easy answer to this question, but there doesn't seem to be...
我正在使用Excel VBA 2003(是的,我知道它已经过时了,但是我不能更改它),我要做的就是列出给定条件下所有可读属性的名称和值.自定义类.
I'm using Excel VBA 2003 (yes, I know it's out-of date, but I can't change this), and all I want to do is list the names and values of all the readable properties in a given custom class.
我想做这样的事情:
类定义(用于名为cFooBar的类)
Option Explicit
Private pFoo As String
Private pBar As String
Public Property Get Foo() As String
Foo=pFoo
End Property
Public Property Get Bar() As String
Bar=pBar
End Property
呼叫代码
Dim myFooBar as cFooBar, P as Property
myFooBar=new cFooBar
For Each P in myFooBar.Properties
Debug.Print P.Name, P.Value
Next
当然,这是行不通的,因为似乎没有自定义类的属性"集合成员(或者至少没有一个您可以得到的集合),并且没有属性"键入其中一个.
Of course, this doesn't work because there doesn't seem to be a "Properties" collection member for custom classes (or at least not one that you can get at), and there isn't a "Property" type either.
有人知道解决这个问题的方法吗?
Does anybody know a way around this?
TIA,
坎贝尔
推荐答案
正如John上面提到的,VBA不支持反射.这是我以前使用过的一种技巧.基本上,您可以创建一个Collection或Dictionary对象来按名称存储属性".
As John mentions above, reflection is not supported in VBA. Here is a hack that I have used before. Basically you can create a Collection or Dictionary object to store your "properties" by name.
Option Explicit
Private pProperties As Object
Public Property Get Properties() As Object
Set Properties=pProperties
End Property
Public Property Let Properties(p as Object)
Set pProperties = p
End Property
Sub Class_Initialize()
Set pProperties = CreateObject("Scripting.Dictionary")
'Add/instantiate your properties here
pProperties("foo") = "this is foo"
pProperties("bar") = "this is bar"
End Sub
通话代码
Dim myFooBar As New cFooBar, P As Variant
For Each P In myFooBar.Properties.Keys()
Debug.Print P, myFooBar.Properties(P)
Next
这篇关于列出VBA 2003中的类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!