2011-02-16 72 views
3

是否有可能通过自定义对象(如MyClass的[])从C#至VBA使用COM?传递对象VBA使用COM互

如果不是,哪个是最好的解决方案来实现它的工作?

+1

一个搜索止跌回升http://stackoverflow.com/questions/375457/cant-instantiate-a-com-object-written-in-c-from-vba-vb6-ok,这可能会感兴趣。 – Fionnuala 2011-02-16 22:15:02

+1

只要你把它变成ComVisible,是的。 – 2011-02-16 22:24:44

回答

6

我假设你在谈论的Excel VBA到C#...

这里的,做它最小的C#类,在项目W默认名称ClassLibrary1的:

using System; 
using System.Runtime.InteropServices; 

namespace Tester 
{ 
    [ClassInterface(ClassInterfaceType.AutoDual)] 
    public class TestClass 
    { 
     public double D { get; set; } // simple property to get, set a double 
     public string S { get; set; } // simple property to get, set a string 
    } 
} 

和这里的VBA来尝试从类:

Private Sub foo() 

Dim X As New ClassLibrary1.TestClass 

X.S = "Hello" 
Debug.Print X.S ' prints "hello" 

X.D = 12 
Debug.Print X.D ' prints a 12 

End Sub 

,这里是你需要做的,使这项工作的多余的东西:

(1) in C# Project...Properties...Build ==> check "Register for COM interop 
(2) in C# Project...Properties...Application...Assembly Information ==> 
    check "Make assembly COM-visible" 
(3) in VBA ... Tools ... References, browse to the C# bin output directory and select the "*.tlb" file 

注:此方案可根据您添加到类什么失败 - 我不认为VBA会“看到” W比默认的构造函数其他静态类或类。您也无法将VB集合映射到.NET集合,但您可以来回传递基本类型(double,long)和基本类型的数组。此外 - 使用“自动模块”选项是一种廉价的方法来获取方法...容易入门,但效率较低,并公开所有方法。更好的实践(但更多的工作)将是建立你自己的接口。如果展开此TestClass的成员以包含您定义的其他类的实例,并且如果您同样通过AutoDual或手动编码的接口公开这些类方法,那么这些类和它们的(非重载)方法同样可见在VBA中(使用Intellisense)。

希望这会有所帮助。