如何启用VBA对象变量的早期绑定到.NET中创建的COM类

时间:2012-02-17 14:57:10

标签: vb.net vba com createobject early-binding

我似乎无法使用我的COM类库(基于.NET)来支持早期绑定。

我在VB.NET 2003中创建一个类库,用于Office 2003 VBA(以及后来的Office 2010)。文档@ StackOverflow和其他地方给我带来了这段代码:

    Imports System.Runtime.InteropServices

    <InterfaceType(ComInterfaceType.InterfaceIsDual), _
    ComVisible(True), _
    Guid("<some valid GUID>")> _
    Public Interface _TestCOMClass
        Function Test() As String
    End Interface

    <ClassInterface(ClassInterfaceType.None), _
    ComVisible(True), _
    Guid("<another valid GUID>"), _
    ProgId("TestCOMDLL.TestCOMClass")> _
    Public Class TestCOMClass
        Implements _TestCOMClass
        Public Function Test() As String Implements _TestCOMClass.Test
            Return "Test value"
       End Function
    End Class

解决方案设置为使用COM Interop进行编译。它成功构建,然后ProgID出现在VBA的References列表中。

我在VBA中使用它,方法是设置适当的引用,然后声明相应类型的变量并实例化我的类。这是神秘的地方。

    Dim EarlyBird As TestCOMDLL.TestCOMClass
    Dim LateBird  As Object

    Set EarlyBird = New TestCOMDLL.TestCOMClass
    ' This is my preferred instantiation method, but results in a 
    ' "Does not support Automation or expected interface" error

    Set EarlyBird = CreateObject("TestCOMDLL.TestCOMClass")
    ' This is my 2nd best instantiation method, 
    ' but results in a Type Mismatch error

    Set LateBird = CreateObject("TestCOMDLL.TestCOMClass")
    MsgBox LateBird.Test
    ' This works, but has all the disadvantages of late binding

所以我可以引用我的库,声明相应类型的对象变量,并实例化我的类,但我不能将实例化的对象引用分配给我的类型变量,只能分配给Object类型的变量。此外,似乎支持实例化New关键字(Intellisense提供库和类作为选项),但在运行时失败。

我的VB.NET代码或构建设置缺少什么能够保持早期绑定工作?

PS:另一种解决问题的方法是我在this StackOverflow thread尝试了解决方案并发现了AnthonyWJones所说的

  

您也可以引用dll并使用早期绑定:

在我的情况下是不正确的......: - (

0 个答案:

没有答案