2013-08-30 83 views
1

的形狀,這是一些可怕的代碼,我想提高:獲取類型下拉列表

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

只需將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); 
      } 
     } 
    } 
} 
+0

謝謝。不幸的是,它不起作用 - 如果(aShape.Type == Microsoft.Office.Core.MsoShapeType.msoFormControl)它從不碰到任何東西。 – cs0815

+0

@csetzkorn?!這應該。你確定你正在尋找一個下拉?也許你在找一個組合框。過濾數據時會創建下拉菜單;該組合框是您從開發人員選項卡添加的控件之一。 – varocarbas

+0

@csetzkorn實際上我現在測試它,並且此代碼同時查找:組合框和下拉列表。你可能依靠ActiveX元素? – varocarbas