繁体   English   中英

使用COM Interop将对象从C#传递到VBA

[英]Passing objects from C# to VBA using COM Interop

是否可以使用COM将自定义对象(如MyClass [])从C#传递给VBA?

如果没有,哪个是最好的解决方案让这个工作?

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

这是一个最小的C#类,在项目中使用默认名称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会“看到”默认构造函数以外的静态类或类。 您也无法将VB集合映射到.NET集合,但您可以来回传递基本类型(double,long)和基本类型的数组。 此外 - 使用的“Autodual”选项是一种廉价的方法来暴露方法......易于上手但效率较低,并暴露所有公共方法。 更好的实践(但更多的工作)是建立自己的界面。 如果展开此TestClass的成员以包含已定义的其他类的实例,并且如果您同样通过AutoDual或通过手动编码接口公开这些类方法,则这些类及其(非重载)方法同样可见在VBA(使用Intellisense)。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM