get shapes of type dropdown list

822 views Asked by At

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?

1

There are 1 answers

6
varocarbas On BEST ANSWER

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);
           }
        }
    }
}