如何在Excel VBA中使用c#类? [英] How to use c# class in Excel VBA?
问题描述
如果有一些特定于c#< - > vba交互的问题,我也想知道这些。
这是一个C#代码。我建立的是一个类库,具有注册COM互操作设置。
当我将生成的.tlb文件添加到VBA引用列表中时,我希望看到有SayCom类的SayCom类有2个方法,square和getCount。我没看到我缺少什么?
using System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Runtime.InteropServices;
[assembly:CLSCompliant(true)]
命名空间SayCom
{
[CLSCompliant(true)]
[ComVisible(true) ]
public class SayCom
{
int count;
public SayCom()
{
count = 0;
}
[ComVisible(true)]
public int square(int x)
{
++ count;
return x * x;
}
[ComVisible(true)]
public int getCount()
{
return count;
}
}
}
这对我有用
using System;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Runtime.InteropServices;
命名空间ClassLibrary1
{
[Guid(BBF87E31-77E2-46B6-8093-1689A144BFC6)]
[ComVisible(true)]
public界面MyMiniSubs
{
int square(int x);
int getCount();
}
[Guid(BBF87E31-77E2-46B6-8093-1689A144BFC7)]
[ClassInterface(ClassInterfaceType.None)]
public class Class1:MyMiniSubs
{
int count;
public Class1()
{
count = 0;
}
[ComVisible(true)]
public int square(int x)
{
++ count;
return x * x;
}
[ComVisible(true)]
public int getCount()
{
return count;
}
}
}
I have a standalone c# applications that does something specific (listens to TCP port and pronounces all strings that arrive to it via speech synthesizer). How can I make the c# class visible to a VBA program, same way other "References" are visible to it? I would appreciate short and clean example. I struggle to find one of those for some reason.
If there are some gotchas specific to c# <-> vba interaction, I would like to know about those too.
Here is a C# code. I build is as a class library with "Register for COM interop" setting. When I add the resulting .tlb file to VBA references list, I expect to see SayCom library that has SayCom class with 2 methods, square and getCount. I do not see that. What am I missing?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
[assembly: CLSCompliant(true)]
namespace SayCom
{
[CLSCompliant(true)]
[ComVisible(true)]
public class SayCom
{
int count;
public SayCom()
{
count = 0;
}
[ComVisible(true)]
public int square(int x)
{
++count;
return x * x;
}
[ComVisible(true)]
public int getCount()
{
return count;
}
}
}
This works for me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ClassLibrary1
{
[Guid("BBF87E31-77E2-46B6-8093-1689A144BFC6")]
[ComVisible(true)]
public interface MyMiniSubs
{
int square(int x);
int getCount();
}
[Guid("BBF87E31-77E2-46B6-8093-1689A144BFC7")]
[ClassInterface(ClassInterfaceType.None)]
public class Class1 : MyMiniSubs
{
int count;
public Class1()
{
count = 0;
}
[ComVisible(true)]
public int square(int x)
{
++count;
return x * x;
}
[ComVisible(true)]
public int getCount()
{
return count;
}
}
}
这篇关于如何在Excel VBA中使用c#类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!