在Excel VBA中使用C#库函数
我的C#库(.net 4.5.2)代码如下所示:
namespace HelloWorld { public class Hello { public string HelloUser(string name) { return "Hello, " + name; } } }
我使用以下代码在AssemblyInfo.cs文件中使该程序集COM可见:
[assembly: ComVisible(true)]
我通过工具 – >引用在VBA代码中添加了对dll的引用,当试图在excel vba中使用相同的命令时,出现运行时错误:429(ActiveX组件无法创build对象)。 我的代码/调用有什么问题:
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
更新通过Toos – > References添加参考并使用F2检查状态
更新#3更新了VBA代码,仍然没有成功。 这一次的错误是:
Run-time error: 429 (ActiveX component can't create object)
你的类没有接口到COM。 你需要用一个[Guid("some guid")]
属性来修饰你的类,如果你希望能够在后期绑定中使用它,并且给它一个[ProgId("Some.Id")]
, [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}."; } }