首页 文章

COM启用了DLL

提问于
浏览
0

我正在尝试创建一个COM DLL . 我编译了代码并用regasm注册了它 . 我还在tBA中添加了tlb作为参考 . 但是,我的VBA项目无法看到这些方法 . 两组代码都在下面 .

COM库 - 编译为DLL,以regasm注册为tlb,将tlb添加到VBA项目引用

using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Globalization;

namespace ClassLibrary1
{
    [Guid("a81acfd7-ca29-4b71-b45d-d9ffd8930036")]
    public interface ITest
    {
        string HelloWorld(string name);
    }

    [Guid("bb212288-fa1a-432a-9456-e1c3bb78923f"), ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class Test : ITest
    {
        public string HelloWorld(string name)
        {
            return "Hello World! I'm " + name;
        }
    }


}

VBA项目 - 简单测试 . 参考tlb补充说 . 编译错误: Call Thing.HelloWorld("Fred") 上找不到方法或数据成员

Sub bob()
    Dim thing As ClassLibrary1.Test
    Call thing.HelloWorld("Fred")
End Sub

1 回答

  • 1

    使用com-visible,因为user1467261建议允许对象的可见性 . 必须使用VBA中的CreateObject访问该对象 . 代码如下 .

    COM库 - 编译为DLL,以regasm注册为tlb,将tlb添加到VBA项目引用

    using System;
    using System.Net;
    using System.Runtime.InteropServices;
    using System.Globalization;
    
    namespace ClassLibrary1
    {
        [Guid("a81acfd7-ca29-4b71-b45d-d9ffd8930036")]
        public interface ITest
        {
            string HelloWorld(string name);
        }
    
        [Guid("bb212288-fa1a-432a-9456-e1c3bb78923f"), ComVisible(true)]
        [ClassInterface(ClassInterfaceType.None)]
        public class Test : ITest
        {
            public string HelloWorld(string name)
            {
                return "Hello World! I'm " + name;
            }
        }
    
    
    }
    

    VBA

    Sub hwn()
        Dim thing As Object
        Dim text As String
        Set thing = CreateObject("ClassLibrary1.Test")
        text = thing.HelloWorld("Fred")
        Debug.Print (text)
    End Sub
    

相关问题