我有兴趣找到如何从 Excel 调用 C# 代码,并且一直在遵循这里的方法https://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to -调用-a-net-library-from-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”和“Any 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),我会得到一个带有消息“Hello”的 MsgBox(woot!)(没有“World” - unwoot!)。因此,它似乎忽略了论点(“世界”),这似乎违背了这样做的目的。
我会很感激任何解释。引用 tlb 文件是件好事吗?为什么我似乎无法将参数传递给 dll/tlb 或从 dll/tlb 获取结果?有一个更好的方法吗?