我假设你在谈论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
}
}
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
以下是使这项工作需要做的额外事情:
(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
Run Code Online (Sandbox Code Playgroud)
注意:这个方案可能会失败,具体取决于你添加到类中的内容 - 我不认为VBA会"看到"默认构造函数以外的静态类或类.您也无法将VB集合映射到.NET集合,但您可以来回传递基本类型(double,long)和基本类型的数组.此外 - 使用的"Autodual"选项是一种廉价的方法来暴露方法......易于上手但效率较低,并暴露所有公共方法.更好的实践(但更多的工作)是建立自己的界面.如果展开此TestClass的成员以包含已定义的其他类的实例,并且如果您同样通过AutoDual或通过手动编码接口公开这些类方法,则这些类及其(非重载)方法同样可见在VBA(使用Intellisense).
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
3708 次 |
| 最近记录: |