Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the named range of a cell - VSTO

Tags:

c#

excel

vsto

I have generated a series of rows using C# and VSTO. I have basically loaded a couple of rows with data and have given each cell a NamedRange. My question is how would I, knowing the beginning row and end row index, traverse each cell and retrieve it's NamedRange. I've tried Excel.Range range = (Excel.Range)m_worksheet.Cells[x,y]; which gets the range fine, but then when I do a range.Name.ToString(); I get "System.__COM...." instead of the name. Can anyone assist?

Thanks

like image 981
Webcognoscere Avatar asked Nov 19 '09 16:11

Webcognoscere


3 Answers

Here is the sample code (take from here) how you can iterate through named range in 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);
            }
        }

    }
like image 114
shahjapan Avatar answered Sep 19 '22 22:09

shahjapan


I know this sucker is old but I just needed this answer so now that I have it I will share: When you build your named ranges you want to handle their Change event, In that handler you'll need some code like this:

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 determines the intersection of 2 ranges, and returns null if it doesn't find one.

like image 39
Nick Daniels Avatar answered Sep 21 '22 22:09

Nick Daniels


I used a cast:

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

Where "target" is a Microsoft.Office.Interop.Excel.Range; The Name included the name of the sheet.

like image 26
Eric Avatar answered Sep 20 '22 22:09

Eric