简体   繁体   English

使用C#中的Excel.Interop检查范围是否具有名称

[英]Check if a Range has a Name using Excel.Interop in C#

I am currently working on Excel Addin Application using C# and Excel Interop. 我目前正在使用C#和Excel Interop开发Excel插件应用程序。 I am looping through a range of cells. 我正在遍历一系列单元格。 I am trying to check if a cell is Named or not. 我正在尝试检查一个单元是否命名。

But when I am trying to add a if condition there is exception thrown if the range is not named. 但是,当我尝试添加if条件时,如果未命名范围,则会引发异常。 The exception is 例外是

System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC System.Runtime.InteropServices.COMException(0x800A03EC):来自HRESULT的异常:0x800A03EC

This is kind of wierd. 这有点奇怪。

if(r.Name == null)
{
    item.name="Not named";
} else 
{
    item.name = r.Name.Name;
}

The exception is thrown at if condition itself, why does the Range object does not return null if it is not named ? 如果条件本身抛出异常,为什么Range对象未命名时不返回null?

Is there a way to check if the range has a Name or not. 有没有一种方法可以检查范围是否具有名称。 I do not seem to find any other solution. 我似乎没有找到其他解决方案。

Any help in this regards is appreciated. 在这方面的任何帮助表示赞赏。

Thanks 谢谢

The exception is thrown at if condition itself, why does the Range object does not return null if it is not named ? 如果条件本身抛出异常,为什么Range对象未命名时不返回null?

That's just the way the Excel object model works, you'll get the same result if you try to access Range.Name from VBA code. 这就是Excel对象模型的工作方式,如果您尝试从VBA代码访问Range.Name,则会得到相同的结果。

Your options would be: 您可以选择:

  • Catch the exception, eg 捕获异常,例如

     public string GetRangeName(range As Range) { try { var name = range.Name; if (name == null) return null; // Won't happen in the current version of Excel, but who knows for a future version return name.Name; } catch(COMException) { return null; } } 
  • or, iterate through the Names collection of the Worksheet and its Workbook, looking for one that references the cell you're interested in. 或者,遍历工作表及其工作簿的Names集合,以查找引用您感兴趣的单元格的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM