Question

I'm trying to write a function that returns a string that represents the type of object currently selected in Excel.

Right now, this is what I have:

public String GetExcelType(dynamic thing)
{   
    if(thing.GetType().GetProperty("ChartStyle") != null)
    {
        return "[CHART]";
    }
    else if (thing.GetType().GetProperty("Cells") != null)
    {
        return "[TABLE]";
    }

    return "[UNKNOWN]";
}

And then later called with:

GetExcelType(oExcelApp.ActiveWindow.Selection);

Problem is, it returns "[UNKNOWN]" every time.

Further confusing the issue, popping open a debug session we can clearly see that the object has the property in question (in this case "Cells"):

enter image description here

I pulled the dynamic.GetType().GetProperty("foo") bit from several other questions (everyone seems to agree this should work) but it seems to flop, here. What am I doing wrong?

Was it helpful?

Solution 2

This seems to be what you need: http://fernandof.wordpress.com/2008/02/05/how-to-check-the-type-of-a-com-object-system__comobject-with-visual-c-net/

Then you could do something like:

public String GetExcelType(dynamic thing)
{   
    Type type = GetExcelTypeForComObject(thing)
    if(type == typeof(Microsoft.Office.Interop.Excel.Chart))
    {
        return "[CHART]";
    }
    else if (type == typeof(Microsoft.Office.Interop.Excel.Range))
    {
        return "[TABLE]";
    }

    return "[UNKNOWN]";
}

OTHER TIPS

You might find this function useful for finding the type of a COM object:

Microsoft.VisualBasic.Information.TypeName(oExcelApp.ActiveWindow.Selection)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top