Monday, August 4, 2014

Getting worksheet from workbook when there is no such worksheet exists.

During application-level excel add-in development sometimes we need to check whether the worksheet is null or not. Consider the following lines -

string myWorkSheetName = "a_worksheet_Name";
Excel.Workbook Wb= Globals.ThisAddIn.Application.ActiveWorkbook;
Excel.Worksheet mySheet = Wb.Worksheets.get_Item(myWorkSheetName) as Excel.Worksheet;

or,

Excel.Worksheet mySheet = Wb.Worksheets[myWorkSheetName] as Excel.Worksheet;

The worksheets indexer ([]) 
or the get_Item method of Worksheets class does not return nullable object. In this case we can take advantage of LINQ -

 Excel.Worksheet mySheet = Wb.Worksheets.Cast().Where(w => w.Name == myWorkSheetName).FirstOrDefault();

If the worksheet does not found then mySheet will contain null.

No comments:

Post a Comment