簡體   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