在Excel VBA中使用C#库函数

时间:2021-10-04 04:48:40

My C# library (.net 4.5.2) code looks like this:

我的C#库(.net 4.5.2)代码如下所示:

namespace HelloWorld
{
    public class Hello
    {
        public string HelloUser(string name)
        {
            return "Hello, " + name;
        }
    }
}

I have made the assembly COM visible in AssemblyInfo.cs file using the following code:

我使用以下代码在AssemblyInfo.cs文件中显示了程序集COM:

[assembly: ComVisible(true)]

I added the reference to the dll in VBA code via Tools ->References and when trying to use the same in excel vba, I am getting Run-time error: 429 (ActiveX component can't create object). What's wrong with my code/call:

我通过工具 - >引用在VBA代码中添加了对dll的引用,当在excel vba中尝试使用它时,我得到运行时错误:429(ActiveX组件无法创建对象)。我的代码/电话出了什么问题:

Excel VBA (2013)

Excel VBA(2013)

Option Explicit

Sub tester()

Dim message As String
Dim User As String

User = "Ronnie"
Dim obj As New HelloWorld.Hello
message = obj.HelloUser(User)

End Sub

UPDATE After adding reference via Toos ->References and checking the status using F2 在Excel VBA中使用C#库函数

更新通过Toos - > References添加引用并使用F2检查状态后

UPDATE #3 Updated the VBA code and still no success. This time the error is:

更新#3更新了VBA代码但仍然没有成功。这次错误是:

Run-time error: 429 (ActiveX component can't create object)

1 个解决方案

#1


3  

Your class exposes no interface to COM. You need to decorate your class with a [Guid("some guid")] attribute and give it a [ProgId("Some.Id")] if you want to be able to use it with late binding, and a [ComDefaultInterface(typeof(IHelloWorld))] that formally describes how members are exposed:

您的类没有公开COM的接口。你需要使用[Guid(“some guid”)]属性来装饰你的类,如果你想能够使用后期绑定和[ComDefaultInterface( typeof(IHelloWorld))]正式描述了成员的暴露方式:

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IHelloWorld
{ 
    string HelloUser(string name);
}

[ComVisible(true)]
[ComDefaultInterface(typeof(IHelloWorld))]
public class HelloWorld : IHelloWorld
{
    public string HelloUser(string name)
    {
        return $"Hello, {name}.";
    }
}

#1


3  

Your class exposes no interface to COM. You need to decorate your class with a [Guid("some guid")] attribute and give it a [ProgId("Some.Id")] if you want to be able to use it with late binding, and a [ComDefaultInterface(typeof(IHelloWorld))] that formally describes how members are exposed:

您的类没有公开COM的接口。你需要使用[Guid(“some guid”)]属性来装饰你的类,如果你想能够使用后期绑定和[ComDefaultInterface( typeof(IHelloWorld))]正式描述了成员的暴露方式:

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IHelloWorld
{ 
    string HelloUser(string name);
}

[ComVisible(true)]
[ComDefaultInterface(typeof(IHelloWorld))]
public class HelloWorld : IHelloWorld
{
    public string HelloUser(string name)
    {
        return $"Hello, {name}.";
    }
}