简体   繁体   English

C#确定Excel中所选对象的类型

[英]C# Determining the Type of the Selected Object in Excel

I'm trying to write a function that returns a string that represents the type of object currently selected in Excel. 我正在尝试编写一个函数,该函数返回一个字符串,该字符串表示当前在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. 问题是,每次都返回“[UNKNOWN]”。

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"): 进一步混淆问题,弹出一个调试会话,我们可以清楚地看到该对象具有相关属性(在本例中为“Cells”):

在此输入图像描述

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. 我从其他几个问题中提取了dynamic.GetType().GetProperty("foo")位(每个人似乎都同意这应该有效)但是它似乎在翻转,这里。 What am I doing wrong? 我究竟做错了什么?

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

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

您可能会发现此函数对于查找COM对象的类型很有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM