获取类型下拉列表的形状

时间:2013-08-30 13:19:08

标签: c# .net excel excel-interop excel-automation

这是一些我想改进的可怕代码:

Excel.Shapes theShapes = excelSheet.Shapes;

foreach (Excel.Shape aShape in theShapes)
{    
    foreach (var groupItem in aShape.GroupItems)
    {
        //Console.WriteLine(Microsoft.VisualBasic.Information.TypeName(groupItem));       
        var s = (Excel.Shape) groupItem;
        if (s is Excel.OLEObject) continue;
        try
        {
            if (s.FormControlType == Excel.XlFormControl.xlDropDown)
            {
                Console.WriteLine("### " + s.Name);
            }
        }
        catch (Exception e)
        {

        }
    }
}

有没有办法更轻松地获取下拉列表?当我尝试获取FormControlType时,如何避免上述异常?

1 个答案:

答案 0 :(得分:1)

只需将try...cath替换为确认其为FormControl的条件。

Excel.Shapes theShapes = excelSheet.Shapes;

foreach (Excel.Shape aShape in theShapes)
{    
    foreach (var groupItem in aShape.GroupItems)
    {
        var s = (Excel.Shape) groupItem;
        if (s is Excel.OLEObject) continue;

        if (s.Type == Microsoft.Office.Core.MsoShapeType.msoFormControl)
        {
           if (s.FormControlType == Excel.XlFormControl.xlDropDown)
           {
               Console.WriteLine("### " + s.Name);
           }
        }
    }
}