Cannon
Cannon

Reputation: 2783

How to find the named range of a cell - VSTO throws exception

To get named range of a cell, heres my code. Works ok if the clicked cell is on first sheet. But the moment I select a cell from some other sheet, it just throws the Exception from HRESULT: 0x800A03EC Error

Saw similar question on stack but dint get the conclusion from those posts: Here is my code:

            Microsoft.Office.Interop.Excel.Workbook _workbook = ThisAddIn.Application.ActiveWorkbook;

            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 = _workbook.Application.Intersect(Target, name.RefersToRange);
                if (intersectRange != null)
                {
                    rangeName = name.Name;
                    break;
                }
            }

Upvotes: 1

Views: 1595

Answers (3)

Another User
Another User

Reputation: 1

try a simpler way to get the name

If Not (ActiveCell.ListObject Is Nothing) Then MsgBox ActiveCell.ListObject.Name End If

Upvotes: 0

Tim Williams
Tim Williams

Reputation: 166196

You can't use Intersect without throwing an error if the ranges are on different sheets. Add a check to see whether each range's Parent property refer to the same sheet, before you try the Intersect()

Upvotes: 4

Kendall Frey
Kendall Frey

Reputation: 44316

It looks to me like Globals.ThisAddIn.Excel is an Application object. It may be a different instance than Globals.ThisAddIn.Application. According to http://www.ureader.com/message/692318.aspx using objects between two Applications can trigger your exception.

Try changing your code to use one or the other Application instance, not both.

Upvotes: 0

Related Questions