Search code examples
c#.netexcelexcel-interopexcel-automation

get shapes of type dropdown list


This is some horrendous code which I would like to improve:

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)
        {

        }
    }
}

Is there a way to obtain drop down lists easier? How can I avoid the above exception when I try to obtain the FormControlType?


Solution

  • Just replace the try...cath with a condition confirming that it is a 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);
               }
            }
        }
    }