0

我有一个在 VBA (Excel) 中使用的 COM 对象(用 C#.NET 构建),枚举 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
4

1 回答 1

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
于 2011-11-10T08:30:30.443 回答