C#Excel检查单元格在VSTO中包含一个名称(C# Excel Check cell contains a name in VSTO)

我试图检查单元格是否包含名称或是否为命名范围,如果没有,我将指定一个名称。 这是我的代码:

if (cell.Name.Name == null) 
{ 
    Globals.ThisWorkbook.Names.Add("Temp", cell);
}
else
{
    // Move on
}

但是,上面的代码将抛出COMException 。 相反,我试图通过这样做来绕过它:

try
{
    if (cell.Name.Name == null) { }
}
catch (COMException)
{
    Globals.ThisWorkbook.Names.Add("Temp", cell);
}

第二个代码片段有效,但我的电子表格受到严重影响。 操作从约80毫秒到1700毫秒。 这可能看起来不多,但我正在循环范围选择。

错误消息是:

System.Runtime.InteropServices.COMException was unhandled by user code
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=""
  ErrorCode=-2146827284
  StackTrace:
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Range.get_Name()
       at ExcelTemplate1.Sheet1.button2_Click(Object sender, EventArgs e) in c:\Users\User\Desktop\ExcelTemplate1\ExcelTemplate1\Sheet1.cs:line 116
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException: 

问题是,有没有更好的方法来检查单元命名范围?


I am trying to check if a cell contains name or is a named range, if not, I will assign a name. Here is my code:

if (cell.Name.Name == null) 
{ 
    Globals.ThisWorkbook.Names.Add("Temp", cell);
}
else
{
    // Move on
}

However, the above code will throw a COMException. Instead, I tried to get around it by doing this:

try
{
    if (cell.Name.Name == null) { }
}
catch (COMException)
{
    Globals.ThisWorkbook.Names.Add("Temp", cell);
}

The second code snippet worked but my spreadsheet is taking a serious performance hit. The operation went from ~80 ms to 1700 ms. This may not seem much but I am looping over a range selection.

The error message was:

System.Runtime.InteropServices.COMException was unhandled by user code
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=""
  ErrorCode=-2146827284
  StackTrace:
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Range.get_Name()
       at ExcelTemplate1.Sheet1.button2_Click(Object sender, EventArgs e) in c:\Users\User\Desktop\ExcelTemplate1\ExcelTemplate1\Sheet1.cs:line 116
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException: 

Question is, is there a better way to check for cell named range?

2023-02-05 17:02

满意答案

您收到错误,因为cell.Name本身引发异常,更不用说cell.Name.Name。

Globals.ThisWorkbook.Names.Item(1)为您提供工作簿中定义的第一个名称。 它给出的值如=Sheet1!$E$10:$F$12=Sheet1!$C$5来表示命名范围所指的内容。

Globals.ThisWorkbook.Names.Item(1).Name将为您提供范围的实际名称。 例如,在你的情况下Temp 。 这是一种检查方法。

其他方式,在您的代码中,您正在检查名称是否为空,如果是,您是否再次分配它。 多次运行此代码没有任何害处:

Globals.ThisWorkbook.Names.Add("Temp", cell);

您可以跳过检查并改为运行此语句。 如果名称已经存在,它将覆盖。 大不了!!!


You are getting an error because cell.Name itself raises exception, let alone cell.Name.Name.

Globals.ThisWorkbook.Names.Item(1) gives you first of the names defined in your workbook. It gives values like =Sheet1!$E$10:$F$12 and =Sheet1!$C$5 to indicate what that named range refers to.

Globals.ThisWorkbook.Names.Item(1).Name shall give you actual name of the range. e.g. Temp in your case. That is one way to check.

Other way, in your code you are checking if the Name is null and if it is you are assigning it again. There is no harm in running this code multiple number of times:

Globals.ThisWorkbook.Names.Add("Temp", cell);

You can skip the check and run this statement instead. If the name is already there, it'll overwrite. Big deal!!!

相关问答

更多

Excel VSTO如何工作?(How does Excel VSTO Work?)

根据这个 (谢谢PintSizedCat)Excel 2003,会发生以下情况: Microsoft Office应用程序检查自定义文档属性以查看是否存在与该文档关联的托管代码扩展。 有关更多信息,请参阅自定义文档属性概述。 如果有托管代码扩展名,应用程序将加载AddinLoader.dll。 这是一个非托管DLL,它是Visual Studio 2005 Tools for Office Second Edition运行时的加载程序组件。 有关更多信息,请参阅Visual Studio Tool...

从Excel加载项vsto访问特定的单元格(access specific cell from excel add-in vsto)

尝试一下这些方面的内容: var excel = Globals.ThisAddIn.Application; var activeSheet = (Worksheet)excel.ActiveSheet; var cell = activeSheet.Range["B1", Type.Missing]; var content = cell.Value2; Try something along these lines: var excel = Globals.ThisAddIn.Applic...

如何使用C#在Excel工作表中获取当前或集中的单元格值(How to get current or focussed cell value in Excel worksheet using C#)

Excel.Range rng = (Excel.Range) this.Application.ActiveCell; //get the cell value object cellValue = rng.Value; //get the row and column details int row = rng.Row; int column = rng.Column; 这是一个快速入门演练 。 Excel.Range rng = (Excel.Range) this.Applicati...

VSTO c#检查单元是否为空(VSTO c# Check if a cell is null)

你正在反思。 Range.Value2返回一个对象。 所以,如果你想检查空引用,只要做 if(Range.Value2 == null) { //blah blah } else { //blah blah } 您可能应该多查看一下在线API文档。 http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.value2(v=office.14).aspx http://msdn.microso...

C#Excel检查单元格在VSTO中包含一个名称(C# Excel Check cell contains a name in VSTO)

您收到错误,因为cell.Name本身引发异常,更不用说cell.Name.Name。 Globals.ThisWorkbook.Names.Item(1)为您提供工作簿中定义的第一个名称。 它给出的值如=Sheet1!$E$10:$F$12和=Sheet1!$C$5来表示命名范围所指的内容。 Globals.ThisWorkbook.Names.Item(1).Name将为您提供范围的实际名称。 例如,在你的情况下Temp 。 这是一种检查方法。 其他方式,在您的代码中,您正在检查名称是否为空,...

C#vsto拖放到单元格,在删除之前获取单元格对象(C# vsto drag drop to cell, get the cell object before dropping)

VSTO(也不是Excel)没有为此提供任何内容。 您可以尝试使用Range类的Locked属性来指示对象是否已锁定。 如果对象被锁定,则此属性返回True;如果在保护工作表时可以修改对象,则返回False;如果指定范围包含已锁定和未锁定的单元格,则返回Null。 Protect方法保护工作表,使其无法修改。 因此,您可以保护工作表,并将可以删除数据的区域的Locked属性设置为false。 希望能帮助到你。 VSTO (nor Excel) doesn't provide anything fo...

使用VSTO C#在Excel单元格下拉列表中列表项是否有任何限制?(Is there any limit on list items in Excel cell dropdown using VSTO C#?)

经过大量的研究,我终于找到了解决方案。 如果您想要在Excel单元格的下拉列表中获取大量数据,那么使用公式是比使用项目List更好的解决方案。 string formula = "='SheetName'!$B$2:$B$" + lastRowIndex; cellRange.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel....

C#Excel VSTO - 取消选择所有单元格(C# Excel VSTO - Deselect all cells)

工作表上始终有一个活动单元格处于活动状态。 你唯一能做的就是选择最不烦人的细胞,比如第一个细胞。 There's always an active cell on the sheet which is active. The only thing you can do is select the least annoying cell, such as the first one.

在C#vsto Excel中粘贴特殊功能(Paste Special in C# vsto Excel)

从http://globalmousekeyhook.codeplex.com/下载dll 添加引用MouseKeyboardActivityMonitor.dll private KeyboardHookListener k_keyListener; private void ThisWorkbook_Startup(object sender, System.EventArgs e) { k_keyListener = new KeyboardHook...

如何使用VSTO从excel中获取单元格值?(How to best fetch a cell value from excel using VSTO?)

使它成为一个对象,然后在从单元格中取出值后找出正确的类型。 我不知道VSTO,但在Excel Interop程序集中,有一个Value2和一个Text属性都返回了对象,并且可以通过多态转换为正确的类型。 VSTO不提供这些吗? Make it an object, then find out the right type after you have gotten the value out of the cell. I don't know about VSTO, but in the Exce...

相关文章

更多

POI 操作Excel公式

在执行这个公式

这种的EXCEL表格 怎么来解析??

如图的EXCEL表格 怎么来解析??

JXLS根据excel模板生成EXCEL并下载

JXLS根据excel模板生成EXCEL并下载,jxl.jar,jxls-core-0.9.9.jar ...

Becoming a data scientist

Data Week: Becoming a data scientist Data Pointed, ...

jxl解析excel并导入数据库

怎样用jxl解析多级表头的excel文件,确定某个单元格cell对应的标题?

lucene读取word,excel,pdf

前面在写lucene入门的时候,例子只能对txt文档建立索引,不能对word,excel,pdf建立索 ...

POI给单元格数据添加超链接

cell.setHyperlink(link)

使用POI操作Excel和Word

前言:今天在项目中看到有小模块是上传Excel解释后保存到数据库的操作,好奇之下去了解了如何使用Apa ...

POI Cells单元格数据处理

创建一个单元格

java+jsp来获取excel的数据?

首先我会在jsp页面上给用户一个上传组件,然后用户上传excel~然后自动后台去解析excel里面的数 ...

最新问答

更多

Python / IPython奇怪的不可重现列表索引超出范围错误(Python/IPython strange non reproducible list index out of range error)

你得到IndexError的原因是你的输入文件显然不是完全用制表符分隔的。 这就是为什么当您尝试访问它时, splits[1]没有任何内容。 您的代码可以使用一些重构。 首先,你正在重复使用if -checks,这是不必要的。 这只是将cds0到7个字符,这可能不是你想要的。 我将以下内容放在一起,以演示如何重构您的代码,使其变得更加pythonic和干燥。 我无法保证它能够与您的数据集一起使用,但我希望它可以帮助您了解如何以不同的方式执行操作。 to_sort = [] # W

故事板从表格单元中延伸出来并显示其详细信息披露按钮(storyboard segue from a tablecell an its Detail Disclosure Button)

我不认为你可以链接一个特定的细节披露按钮瓦特/赛格。 我的故事板是非常程序化的B / C我使用了很多定制CGRect等。 所以我倾向于使用这样的东西: -(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"ViewControllerIdentifer"

我们可以将Gherkin功能文件与testcomplete集成(Can we integrate Gherkin feature files with testcomplete)

TestComplete不支持Gherkin功能文件。 但是,TestComplete具有SDK,因此可以自己为此创建扩展。 TestComplete does not support Gherkin feature files. However, TestComplete has SDK so it is possible to create an extension for this by yourself.

TrustAllCertificatesCallback被忽略(TrustAllCertificatesCallback is ignored)

我没有做过这样的事情,但看看我认为可以看出错误的例子。 试试这个代码: static class Program { static void Main() { var tcpclient = new TcpClient("remote.example.com", 443); var tcpstream = tcpclient.GetStream(); var sslstream = new SslStream(tcpstream,

返回嵌套元素的索引(Return index of nested element)

您需要获取父li元素的索引。 否则,您将获得列表项内锚点的索引,该索引始终为零。 $(this.parentNode).index(); You need to get the index of the parent li element. Otherwise you are getting the index of the anchor inside the list item, which will always be zero. $(this.parentNode).index();

在数组中重新编号元素的有效方法(Efficient way of re-numbering elements in an array)

您需要多次迭代列表,我认为没有办法解决这个问题。 毕竟,在开始更改元素(第二遍)之前,首先必须确定不同元素的数量(第一遍)。 但是请注意,由于对index的重复调用而not in列表中具有O(n),因此可能具有最多O(n ^ 2)的不同元素的数量。 或者,您可以使用dict而不是value_map的list 。 字典比列表具有更快的查找速度,因此,复杂性应该确实在O(n)的数量级上。 您可以使用(1)字典理解来确定旧值到新值的映射,以及(2)用于创建更新子项的列表理解。 value_map =

Express app定义的`static`文件夹无法正常工作(Express app defined `static` folder not working properly)

选项1 你可以改变这一行: app.use( express.static(__dirname + '/puplic')); //my public folder. 至 app.use('/oneTime', express.static(__dirname + '/puplic')); //my public folder 选项2 我假设你在公共文件夹中有一个js文件夹,然后你需要更改你的HTML代码:

使用node.js和socket.io每秒广播一次(Using node.js and socket.io to broadcast every second)

对于计时器值,请在服务器端本身每秒更新本地计时器。 每当有任何用户进来时,给他这个值以及计时器的总值。 然后客户端将根据dandavis评论在本地启动自己的计时器,但在服务器端保留一些间隔,如15或10秒,服务器将广播当前计时器值,以便客户端相应地进行同步。 简而言之,服务器将每隔10(n:你决定)秒后广播,但它将在本地每秒更新定时器变量。 每当客户端进入时,它将获得总计时器值和当前计时器值。 广播当前出价的休息功能可以以正常方式完成。 For timer value, keep updatin

如何让XMLSerializer将命名空间添加到嵌套对象中的属性?(How do I get the XMLSerializer to add namespaces to attributes in nested objects?)

IXmlSerializable也许? 注意我还添加了(对A ): [XmlElement("A", Namespace = "http://www.example.com/namespace")] public TestSoapHeaderTypeValuePair A {...} 代码如下: public class TestSoapHeaderTypeValuePair : IXmlSerializable { private string _type; private