![](/img/trans.png)
[英]How to create Web application using Xamarin Forms(UWP) and C# in visual studio 2019
[英]How to Create a C# COM Object using Visual Studio 2019
I have upgraded from Windows 7/Visual Studio 2015 to Windows10/Visual Studio 2019. I wish to create a C# COM object which I can call from Excel(365) VBA code.
Using Win 7/Visual Studio 2015 the following very simple code compiles as a C# class library and creates a COM object that I can call successfully from Excel 2013 VBA:-
using System.Runtime.InteropServices;
namespace TestLib {
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class C_Hello {
public string Hello() {
return "Hello";
}
}
}
在裝配信息中,我勾選了復選框“使裝配 COM 可見”,在構建信息中,我勾選了復選框“注冊 COM 互操作”
Excel 2013 VBA 代碼同樣簡單:
Sub Test()
Dim x As TestLib.C_Hello
Set x = New TestLib.C_Hello
ActiveSheet.Range("C3").Value = x.Hello
End Sub
其中 TestLib 是在 Visual Studio 中創建的 C# COM 模塊。
在 Win 7/VS2015/Excel 2013 環境中一切正常,但在 Win 10/VS2019 下傳輸和編譯后,Excel 365 VBA 代碼錯誤如下:-
Set x = New TestLib.C_Hello
帶有錯誤消息
運行時錯誤“-2147221164 (80040154)”
Class 未注冊
誰能告訴我我必須做什么才能在 Windows 10 / VS2019 / Excel 365 環境中工作。? 是 Windows 10 還是 Visual Studio 2019 做事不同?
確保 excel 的位數與您在 VS 中的構建相匹配。 您可能需要為您的項目添加 x86 或 x64 版本。
可以注冊 AnyCpu 程序集,但 Visual Studio 不會使用兩者的“注冊 COM 互操作”來注冊。 您可以通過手動運行 32 位和 64 位版本的 regasm 或從構建后腳本手動執行此操作。
否則,您可以使用 ProcMon 檢查 Excel 正在尋找和未找到的注冊或文件。 但是警告,除非您熟悉運行時發生的“正常”錯誤,否則很容易排除紅鯡魚故障。 我建議通過“路徑”過濾包含“TestLib.C_Hello”然后從那里追逐它。
Win10 / VS2019 環境中的解決方案是將 VS 的 Build 選項卡中的Platform Target從Any CPU更改為x64 ,然后它就可以工作了。
在 Win7 / VS2015 環境中,任何 CPU的平台目標都可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.