C#/VBA COM 互操作中的错误处理
我有一个从 Excel VBA 调用的 C# DLL,我已通过 COM Callable Wrapper/COM Interop 公开了该 DLL。我希望能够将 C# 代码中发生的任何异常传递到 VBA 客户端。有没有推荐的方法来做到这一点?谢谢。
I have a C# DLL being called from Excel VBA which I have exposed via a COM Callable Wrapper / COM Interop. I want to be able to pass any exceptions which occur in the C# code up onto the VBA client. Are there any recommended approaches to doing this ? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以创建您自己的异常,将 HRESULT 错误代码传达回 VBA 或其他基于 COM 的调用方。下面是使用 E_FAIL 的示例:
这里是 MSDN描述该过程的文章。
这将为您提供与 VB6 中相同的 VBA 错误支持,它将向用户显示您选择的错误消息以及您选择的 HRESULT。
It is possible to create your own exceptions that communicate HRESULT error codes back to VBA or other COM based callers. Here's an example that uses E_FAIL:
Here is an MSDN article that describes the process.
This should give you the same VBA error support you had in VB6, it will display the error message of your choice to the user along with the HRESULT that you choose.
几年前,我对 COM 函数调用返回错误信息有模糊的记忆。 COM 函数不应返回异常。 COM 函数中发生错误的事实由返回值表示。 S_OK(0)表示成功。负数意味着失败。您可以使用不同的负数来传递基本错误类型,但是对于更具体的错误信息,您必须在 COM 对象上实现 IErrorInfo 接口。
完成此操作后,Visual Basic 6 和 Visual Studio 2000 在 Visual Basic 中可以很好地处理 COM 错误,但旧版本的 VBA 却不能。
如果有人最近使用过 COM,他们很可能能够填写详细信息,并纠正我多年来记忆模糊的地方。
让我惊讶的是,实现一个新的 COM 包装器代码,将异常转换为记录的 COM 错误并不是一件容易的通用事情,并且可以制作一个手工编码的版本,但同样,您需要了解 COM 编程。
重新设计您的 .NET 对象,以便它们通过在对象中调用 getlasterror() 方法来报告错误详细信息将是一个明智的解决方法。
Years ago I have vague memories of returning error information on COM function calls. COM functions should not return exceptions. The fact that an error happened in the COM function is signalled by the return value. S_OK (0) meant success. negative numbers meant failure. You could use different negative numbers to pass basic error types, however for more specific error information, you had to implement the IErrorInfo interface on the COM object.
Having done this, Visual Basic 6 and Visual Studio 2000 handled COM errors nicely in Visual Basic, however older versions of VBA didnt.
If someone has used COM much more recently they may well be able to fill in the details, and correct where my memory has gone hazy over the years.
It strikes me that implementing a new COM wrapper code that translated exceptions into documented COM errors would not be an easy generic thing and that making a hand coded version could be done, but again, you would need to understand COM programming.
Redesigning your .NET objects so they reported error detail by calling your getlasterror() method in your object would be a sensible workaround.