While working with excel using C# you can require to find the last used row or column in a range. Here in this post, we are providing you the code snippets that will simplify your task and you can easily find last filled column or row of excel sheet in the given range.
We have given below various conditions of finding last filled column or row in excel.
Get the last used Row in Worksheet
Below given C# code snippet finds the last filled row in excel sheet and stores its row number in rowIndex variable of int type.
Int rowIndex = excelSheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
Get the last used Column in Worksheet
Below given C# code snippet finds the last filled column in excel sheet and stores its column number in colIndex variable of int type.
Int colIndex = excelSheet.Cells.Find("*", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Microsoft.Office.Interop.Excel.XlSearchOrder.xlByColumns, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Column;
Get Last used Row from Specified Cell
This C# code snippet work like ctrl+shift+end combination in excel and stores row number of last used row in rowIndex variable of int type.
Microsoft.Office.Interop.Excel.Range xlStartRange = (Microsoft.Office.Interop.Excel.Range)excelSheet.Cells[2, 1];
int rowIndex = xlStartRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlToRight).Row;
Get Last used Column from Specified Cell
This C# code snippet work like ctrl+shift+right combination in excel and stores column number of last used column in colIndex variable of int type.
Microsoft.Office.Interop.Excel.Range xlStartRange = (Microsoft.Office.Interop.Excel.Range)excelSheet.Cells[2, 1];
int colIndex = xlStartRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlDown).Column;