Domanda

I am currently working on Excel Addin Application using C# and Excel Interop. 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. The exception is

System.Runtime.InteropServices.COMException (0x800A03EC): Exception from 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 ?

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

È stato utile?

Soluzione

The exception is thrown at if condition itself, why does the Range object does not return null if it is not named ?

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.

Your options would be:

  • Catch the exception, e.g.

    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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top