Excel 2010 VSE 2012 C#dll和tlb - 无法创建对指定文件的引用

时间:2013-10-04 01:07:18

标签: c# .net excel vba typelib

我有兴趣找到如何从Excel调用C#代码,并且一直在遵循这里的方法https://richnewman.wordpress.com/2007/04/15/a-beginner%E2%80%99s-guide-to-calling-a-net-library-from-excel/

C#代码是一个名为DotNetClass.cs的“Hello World”示例

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),我会得到一个消息为“Hello”的消息(没有“World” - unwoot!)的MsgBox(woot!)。所以,似乎忽略了这个论点(“世界”),这似乎打败了这样做的目的。

我很感激任何解释。引用tlb文件是件好事吗?为什么我似乎无法将参数传递给dll / tlb或从dll / tlb获取结果?有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

我得到了它的工作。问题出现了,因为C#是强类型的,而VBA是松散类型的。

在VBA行

MsgBox testClass.DotNetMethod(“World”)

一个“东西”(技术上是var,我相信),其值为“World”,传递给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”