2010-06-11 47 views
3
錯誤

我使用下面的代碼處理「未找到細胞」。在Excel中

Excel.Range rngTemp; 
Excel.Range rngErrorRange; 

Excel._Worksheet Sheet1 = (Excel._Worksheet)xlCTA.Sheets["Sheet1"]; 
rngTemp = wsCTAWK11.UsedRange; 
rngErrorRange = rngTemp.SpecialCells(Excel.XlCellType.xlCellTypeFormulas, Excel.XlSpecialCellsValue.xlErrors); 

工作的Excel VSTO應用程序,並找到錯誤的細胞在工作表中找到真正的錯誤單元格時,那麼我沒有任何問題,但是當我沒有任何在這些工作表錯誤的細胞,我得到下面的異常

**threw an exception of type 'System.Runtime.InteropServices.COMException' 
    base {System.Runtime.InteropServices.ExternalException}: {"No cells were found."}** 

如何處理這個......請幫助

回答

1

捕獲異常並處理它,但是你想?

1
try 
{ 
    Excel.Range rngTemp; 
    Excel.Range rngErrorRange; 

    Excel._Worksheet Sheet1 = (Excel._Worksheet)xlCTA.Sheets["Sheet1"]; 
    rngTemp = wsCTAWK11.UsedRange; 
    rngErrorRange = rngTemp.SpecialCells(Excel.XlCellType.xlCellTypeFormulas, 
Excel.XlSpecialCellsValue.xlErrors); 
} 
catch (System.Runtime.InteropServices.COMException ex) 
{ 
    //Handle here 
} 
+1

是啊我現在正在這樣做...但想知道是否有任何檢查,我可以做之前行rngErrorRange = rngTemp.SpecialCells(Excel.XlCellType.xlCellTypeFormulas, Excel.XlSpecialCellsValue.xlErrors); – Sathish 2010-06-11 12:13:56

0

而不是使用內置的SpecialCells方法編寫自己的擴展方法,該方法將調用包裝爲帶有錯誤處理的myRange.SpecialCells。

我做了以下內容:

public static Range SpecialCellsCatchError(this Range myRange, XlCellType cellType) 
    { 
     try 
     { 
      return myRange.SpecialCells(cellType); 
     } 
     catch (System.Runtime.InteropServices.COMException ex) 
     { 
      return null; 
     } 
    } 

然後,你將不得不考慮空,但它不會引發錯誤。