2009-11-19 86 views
6

我已经使用C#和VSTO生成了一系列行。我已经基本上加载了几行数据,并给每个单元一个NamedRange。我的问题是,如何知道开始行和结束行索引,遍历每个单元格并检索它的NamedRange。我试过Excel.Range范围=(Excel.Range)m_worksheet.Cells [x,y];它的范围很好,但是当我做一个range.Name.ToString();我得到“System .__ COM ....”而不是名称。 任何人都可以协助吗?如何查找单元格的命名范围 - VSTO

感谢

回答

8

下面是示例代码(take from here)你怎么可以通过在Excel命名范围迭代。

private Excel.Workbook m_workbook; 
object missing = Type.Missing; 

    public void testNamedRangeFind() 
    { 
     m_workbook = Globals.ThisAddIn.Application.ActiveWorkbook; 
     int i = m_workbook.Names.Count; 
     string address = ""; 
     string sheetName = ""; 

     if (i != 0) 
     { 
      foreach (Excel.Name name in m_workbook.Names) 
      { 
       string value = name.Value; 
       //Sheet and Cell e.g. =Sheet1!$A$1 or =#REF!#REF! if refers to nothing 
       string linkName = name.Name; 
       //gives the name of the link e.g. sales 
       if (value != "=#REF!#REF!") 
       { 
        address = name.RefersToRange.Cells.get_Address(true, true, Excel.XlReferenceStyle.xlA1, missing, missing); 
        sheetName = name.RefersToRange.Cells.Worksheet.Name; 
       } 
       Debug.WriteLine("" + value + ", " + linkName + " ," + address + ", " + sheetName); 
      } 
     } 

    } 
0

你需要遍历Names集合找到namedrange

2

我知道这傻逼是旧的,但我只需要这个答案所以现在我有它,我将分享: 当你建立你的命名范围要处理自己的Change事件,在该处理程序你会需要如下代码:

foreach (Excel.Name name in Globals.ThisWorkbook.Name) 
{ 
if (Application.Intersect(name.RefersToRange, Target) != Null) //Target is the single parameter of our handler delegate type. 
{ 
// FOUND IT!!!! 
} 
} 

Application.Intersect确定2个范围的交集,如果找不到一个,则返回null。

1

我用铸造:

((Excel.Name)target.Name).Name 

如果 “目标” 是Microsoft.Office.Interop.Excel.Range;该名称包括该工作表的名称。

1

我想是这样的:工作如果单元的第一片的一部分,但我在其他一些纸张上单击单元格,并使用该函数的那一刻让我从HRESULT 异常:0x800A03EC错误

我代码是这样:

Microsoft.Office.Interop.Excel.Workbook _workbook = Globals.ThisAddIn.Excel.CurrentWorkbook.InteropReference; 
      Microsoft.Office.Interop.Excel.Range Target = (Microsoft.Office.Interop.Excel.Range)Globals.ThisAddIn.Application.ActiveCell; 
      foreach (Microsoft.Office.Interop.Excel.Name name in _workbook.Names) 
      { 
       Microsoft.Office.Interop.Excel.Range intersectRange = Globals.ThisAddIn.Excel.CurrentWorkbook.InteropReference.Application.Intersect(Target, name.RefersToRange); 

       if (intersectRange != null) 
       { 
        rangeName = name.Name; 
        break; 
       } 
      } 
0

这为我工作

 var ranges = activeworkBook.Names; 
     int i = 1; 
     while (i <= ranges.Count) 
     { 
      String currentName = ranges.Item(i, Missing.Value, Missing.Value).Name; 
      if (currentName.Equals(namedRangeToBeDeleted)) 
      { 
       ranges.Item(i, Type.Missing, Type.Missing).Delete(); 
      } 
      else 
      { 
       i++; 
      } 
     } 

从接过参考210并替换为引用实际的单元格地址。

0

上面的示例使用m_workbook.Names。在我的情况下,我需要在特定的工作表(ActiveWorksheet)上找到命名范围。但是,这似乎不起作用:名称列表保持空白。使用工作簿访问命名范围时,它可以工作。 (VS 2015,Office 2016)

相关问题