VBA - 使用类的文本名称创建一个新对象 [英] VBA - Create a new object using the text name of the class
问题描述
有没有办法通过使用类的文本名称将对象设置为类的新实例?
Is there a way to set an object to the new instance of a class by using the text name of the class?
我将有一个类库,并且根据一些其他变量,我想在运行时得到这些类之一。
I will have a library of classes, and depending on some other variable, I want to get one of these classes at runtime.
例如我有CTest1,CTest2,CTest3
E.g. I have "CTest1", "CTest2", "CTest3"
我的功能类似于以下
Function GetTestClass(lngClassNo as long) as Object
Dim strClassName as String
strClassName = "CTest" & CStr(lngClassNo)
Set GetTestClass = New instance of class(strClassName)
End Function
推荐答案
VBA中没有反思,所以我不认为这是可能的。你必须像下面那样做一些类似的事情:
There's no reflection in VBA, so I don't think this is possible. You'd have to do something like the following I'm afraid:
Function GetTestClass(lngClassNo as long) as Object
Select Case lngClassNo
Case 1
Set GetTestClass = New CTest1
Case 2
Set GetTestClass = New CTest2
...
End Select
End Function
除非是您的CTest类在COM DLL中定义,在这种情况下,您可以使用CreateObject语句。您将需要使用VB6创建这样一个DLL,但不能在Excel,Access等中创建DLL。
Unless that is your CTest classes are defined in a COM DLL, in which case you could use the CreateObject statement. You would need to use VB6 to create such a DLL though, you can't create DLLs in Excel, Access, etc.
Function GetTestClass(lngClassNo as long) as Object
Set GetTestClass = CreateObject("MyDll.CTest" & lngClassNo)
End Function
这篇关于VBA - 使用类的文本名称创建一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!