C# 中 Excel 互操作中的 HRESULT 代码

问题描述 投票:0回答:2

我正在寻找一种在使用 Excel 进行互操作时在 C# 中输出错误的干净方法。

当文件不“正确”时,会出现类似“blabla HRESULT:0x800AC472”的消息。

我宁愿想要一条类似“使用的文件有这个或那个问题”的消息。为了做到这一点,我需要知道每个 HRESULT 映射到什么错误?

如何获得这样的错误列表?

我查看了MSDN,找到了一些描述,但我似乎找不到像上面提到的“0x800AC472”那样的所有代码的列表。

c# excel error-handling interop hresult
2个回答
3
投票

我的 Excel HRESULT 代码 0x800AC472 为

VBA_E_IGNORE
,这表明 Excel 已“暂停对象浏览器”。

在某些情况下,Excel 将拒绝所有传入的 COM 请求。发生这种情况的两种情况是用户

  • 正忙于编辑公式,或者
  • 在 Excel 工作表上按下鼠标按钮。

很可能还有其他情况 - 例如,当 Excel 忙于计算时,我不确定错误代码是什么。

如果您正在执行 COM 自动化来与交互使用的 Excel 实例对话,则您对 Excel 进行的任何 COM 调用都可能返回此错误。我对 Excel-DNA (其中互操作总是从 Excel 进程内的加载项发生)采取的一种方法是尝试调用 Application.Run(...) 来运行加载项中的宏。一旦 Application.Run 调用成功,宏将在主 Excel 线程上运行,其中 COM 请求不会因 Excel 挂起 COM 调用而失败。

Excel 可能出现的其他一些 COM 错误包括:

    const uint RPC_E_SERVERCALL_RETRYLATER = 0x8001010A;
    const uint RPC_E_CALL_REJECTED = 0x80010001; // Not sure when we get this one?
                                                 // Maybe when trying to get the Application object from another thread, 
                                                 // triggered by a ribbon handler, while Excel is editing a cell.
    const uint VBA_E_IGNORE = 0x800AC472;        // Excel has suspended the object browser
    const uint NAME_NOT_FOUND = 0x800A03EC;      // When called from the main thread, but Excel is busy anyway.

0
投票

当然不完整,但常见的是:

Dim table As New Dictionary(Of Integer, String) From {
    {&H800A07D0, "#NULL!"},
    {&H800A07D7, "#DIV/0!"},
    {&H800A07DF, "#VALUE!"},
    {&H800A07E7, "#REF!"},
    {&H800A07ED, "#NAME?"},
    {&H800A07F4, "#NUM!"},
    {&H800A07FA, "#N/A"}
}

Public Function ExcelErrorCode(code As Integer) As String

    Dim result = ""

    table.TryGetValue(code, result)

    Return result

End Function
© www.soinside.com 2019 - 2024. All rights reserved.