C#确定Excel中所选对象的types

我想写一个函数返回一个string,表示当前在Excel中select的对象的types。

现在,这是我所拥有的:

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

然后后来打电话给:

 GetExcelType(oExcelApp.ActiveWindow.Selection); 

问题是,它每次都返回“[UNKNOWN]”。

进一步混淆这个问题,popup打开一个debugging会话,我们可以清楚地看到该对象有问题的属性(在这种情况下“单元格”):

在这里输入图像描述

我拉动dynamic.GetType().GetProperty("foo")从其他几个问题(大家似乎同意这应该工作)位,但似乎在这里翻牌。 我究竟做错了什么?

这似乎是你所需要的: http : //fernandof.wordpress.com/2008/02/05/how-to-check-the-type-of-a-com-object-system__comobject-with-visual-c-净/

那么你可以做一些事情:

 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]"; } 

您可能会发现这个function对于查找COM对象的types很有用:

 Microsoft.VisualBasic.Information.TypeName(oExcelApp.ActiveWindow.Selection)