声明:本文修改于vba调用c#dll - crhdyl - 博客园 (cnblogs.com),向原作者致敬,若有不妥,及时联系。
1.创建framework 的dll项目
2.编写导出接口
[Guid("154BD6A6-5AB8-4d7d-A343-0A68AB79470B")]
public interface MyCom_Interface
{
[DispId(1)]
int Add(int a, int b);
[DispId(2)]
string[] GetFiles(string path);
}
3.创建事件接口。
[Guid("D11FEA37-AC57-4d39-9522-E49C4F9826BB"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface MyCom_Events
{
}
4.创建具体类:
[Guid("2E3C7BAD-1051-4622-9C4C-215182C6BF58"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(MyCom_Events))]
public class Class1 : MyCom_Interface
{
public int Add(int a, int b)
{
return a + b;
}
string[] MyCom_Interface.GetFiles(string path)
{
string[] a = { "a", "b" };
return a;
}
}
5.设置项目属性,勾选“是程序集COM可见",勾选”为COM互操作注册“(也可以自己注册),勾选”为程序集签名“,并生成签名。
6.VBA 引用-浏览,找到生成的tlb文件,勾选
7.vba中使用
Sub d()
Dim ds As Variant
Dim io As MyCom.Class1
Set io = New MyCom.Class1
For Each ds In io.GetFiles("sdf")
MsgBox ds
Next
End Sub
8.所有C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace MyCom
{
[Guid("154BD6A6-5AB8-4d7d-A343-0A68AB79470B")]
public interface MyCom_Interface
{
#[DispId(1)]为函数的标识。如果有多个函数可相应的在函数前面加[DispId(2)], [DispId(3)]…
[DispId(1)]
int Add(int a, int b);
[DispId(2)]
string[] GetFiles(string path);
}
[Guid("D11FEA37-AC57-4d39-9522-E49C4F9826BB"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface MyCom_Events
{
}
#InterfaceType表示向COM公开的方式,这里选择为以调度的方式向COM公开
[Guid("2E3C7BAD-1051-4622-9C4C-215182C6BF58"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(MyCom_Events))]
public class Class1 : MyCom_Interface
{
public int Add(int a, int b)
{
return a + b;
}
string[] MyCom_Interface.GetFiles(string path)
{
string[] a = { "a", "b" };
return a;
}
}
}
9.VBA调用代码
Sub d()
Dim ds As Variant
Dim io As MyCom.Class1
Set io = New MyCom.Class1
'也可使用后期绑定代码:Set io = CreateObject("MyCom.Class1")
For Each ds In io.GetFiles("sdf")
MsgBox ds
Next
End Sub
10.注意事项
1。所要导出的类必须为公有;
2。所有属性、方法也必须为公有;
3。要导出的属性、方法必须用接口方式;如果没有在接口中声明,即使该方法(属性)为公有,也不能正常导出到COM。但他们可以被别的.NET程序所使用;
4。所有的事件也必须用接口方式;
最后,再次强调,本文借鉴修改于vba调用c#dll - crhdyl - 博客园 (cnblogs.com),向传播知识的作者致敬。