我有一个COM对象(使用C#.NET构建)我在VBA(Excel)中使用它并且很好地枚举COM对象的字段并自动引用它们。在.NET中,这可以通过反射来完成。有没有办法在VBA中这样做?
所以,而不是
Dim x As MyCOMObject
Set x = New MyCOMObject
x.f1 = 1
x.f2 = 2
x.f3 = 3
更像是:
Dim x As MyCOMObject
Set x = New MyCOMObject
For i = 0 to COMFieldCount(x) - 1
SetCOMField(x, GetCOMFieldName(i), i+1)
Next i
答案 0 :(得分:1)
您可能需要稍微改进一下这个代码,但它大致与您要求的完全相同。 首先,您需要添加对“Typelib信息”TLBINF32.dll的引用。我不确定这是否是Windows的一部分,或者我的机器上安装了许多SDK,但它位于System32文件夹中。
我假设您正在设置COM对象的属性,因此您将调用“property put”函数来设置对象的值。您可能需要检查这些属性的数据类型,我的代码中没有进行任何数据类型转换。
代码如下所示:
'Define the variables
Dim tliApp As TLI.TLIApplication
Dim typeinfo As TLI.typeinfo
Dim interface As TLI.InterfaceInfo
Dim member As TLI.MemberInfo
'Initialize typelib reflector
Set tliApp = New TLI.TLIApplication
'Get the type information about myObject (the COM object you want to process)
Set typeinfo = tliApp.ClassInfoFromObject(myObject)
'Set all properties of all the object's interfaces
For Each interface In typeinfo.Interfaces
For Each member In interface.Members
'If this is a "property put" function
If member.InvokeKind = INVOKE_PROPERTYPUT Then
'Invoke the mebmer and set someValue to it.
'Note that you'll probably want to check what datatype to use and do some more error checking
CallByName myObject, member.Name, VbLet, someValue
End If
Next
Next