![](/img/trans.png)
[英]c# excel dll - can't add a reference to the specified file - regasm
[英]Excel 2010 VSE 2012 C# dll and tlb - Can't create reference to specified file
我有興趣查找如何從Excel調用C#代碼,並且一直在遵循這里的方法https://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to從excel /調用一個網絡庫 。
C#代碼是一個“ Hello World”示例,稱為DotNetClass.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DotNetLibrary
{
public class DotNetClass
{
public string DotNetMethod(string input)
{
return "Hello " + input;
}
}
}
生成配置已選中“注冊COM互操作”和“使程序集COM可見”。 我還具有“ .NET Framework 4.5”和“任何CPU”選項(我正在64位計算機上工作)。 我嘗試了一些NET版本和CPU選項,但均未成功。 我已經清洗並重建了好幾次。
在Excel 2010中,我無法創建對DotNetLibrary.dll的引用。 我可以瀏覽到它,甚至可以在同一位置-DotNetLibrary.tlb創建對文件的引用。
來自Excel的電話是
Private Sub TestDotNetCall()
Dim testClass As New DotNetClass
MsgBox testClass.DotNetMethod(“World”)
End Sub
...這幾乎可行。 如果我運行VBA代碼(F5),則會收到一個MsgBox(嗚嗚!),消息為“ Hello”(沒有“ World”-嗚嗚!)。 因此,它似乎忽略了論點(“世界”),這似乎違背了這樣做的目的。
我將不勝感激。 引用tlb文件是件好事嗎? 為什么我似乎無法將參數傳遞給dll / tlb或從dll / tlb獲得結果? 有一個更好的方法嗎?
我知道了。 出現問題是因為C#是強類型的,而VBA是松類型的。
在VBA行中
MsgBox testClass.DotNetMethod(“World”)
具有“ World”值的“事物”(從技術上講,是var
)傳遞給DotNetMethod。 問題在於DotNetMethod不知道“世界”是什么類型的東西,因此它會忽略它。
解決方案是在VBA中明確定義“世界”的類型,如下所示
Private Sub TestDotNetCall()
Dim testClass As New DotNetClass
Dim s As String
s = "World"
MsgBox (testClass.DotNetMethod(s))
End Sub
...因此,“ Hello World”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.