如何修复在 VBA 项目中导入自定义 DLL 时出现的 运行 错误 430

How can I fix Run-time error 430 from importing custom DLL in VBA project

我为此苦苦挣扎了几个小时,但我找不到我做错了什么。

我创建了一个新的 C# dll 项目,这里是其中唯一 class 的内容:

using System;
using System.Runtime.InteropServices;

namespace PolygonSl {

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class Config {

        [ComVisible(true)]
        public string GetCompany() {
            return "POL";
        }
    }
}

我基本上删除了它的所有内容以使其正常工作,唯一的参考是 System

我检查了 Assembly Information 上的 Make assembly COM-Visible 标志并且我的项目已签名(代码库需要接缝)。

编译正常,然后我调用RegAsm.exe,给它我的dll,我添加/codebase/tlb,命令成功。

当我转到我的 VBA 项目时,我可以将我的新 tlb 文件添加到引用中,工作正常。之后,我可以在我的代码中使用它,自动完成功能正常运行,我可以编译没有错误。

然后,当我执行时,我得到了这个:

Run-time error '430':
Class does not support Automation or does not support expected interface

这是我在 VBA 中的代码示例:

Private Sub Button1_Click()
    'With CreateObject("PolygonSl.Config")
    With New PolygonSl.Config
        MessBox .GetCompany, MB_OK, "Test"
    End With
End Sub

我尝试了后期绑定,我的代码 运行 没问题,但我希望能够使用自动完成功能。

任何人对我可以尝试让它发挥作用有什么建议吗?

编辑(在我的环境中添加一些细节)

我认为您需要定义一个接口才能看到 getcompany。

using System;
using System.Runtime.InteropServices;

namespace PolygonSl
{
    [Guid("6DC1808F-81BA-4DE0-9F7C-42EA11621B7E")]
    [System.Runtime.InteropServices.ComVisible(true)]
    [System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IConfig
    {
        string GetCompany();
    }

    [Guid("434C844C-9FA2-4EC6-AB75-45D3013D75BE")]
    [System.Runtime.InteropServices.ComVisible(true)]
    [System.Runtime.InteropServices.ClassInterface(ClassInterfaceType.None)]
    public class Config : IConfig
    {
        public string GetCompany()
        {
            return "POL";
        }
    }
}

您可以将光标放在class 定义中并使用Edit.Refactor.ExtractInterface 来自动生成界面。

我不得不承认我在这方面的能力绝对处于优势地位,以上内容是根据我在其他地方看到的示例汇总而成的。

编辑

以下测试代码在我的电脑上运行正常

Option Explicit
Sub polygontest()

    Dim my_polygon As SOPolygon.Config
    Set my_polygon = New SOPolygon.Config
    Debug.Print my_polygon.GetCompany

End Sub

其中 SOPolygon 是项目名称。