I have a Microsoft.Office.Interop.Excel.Range
object and want to estimate the end-coordinates of that range ie (last column, last row).
There are no properties like LastCol
, LastRow
. The only properties are Column
and Row
, which specify the first cell. But how can I get the last cell of the range?
there is two way to do this :
Using Worksheet.UsedRange
to determine the range. This will give you a range like A1:F10, or use Worksheet.UsedRange.SpecialCells(IExcel.XlCellType.xlCellTypeLastCell)
to obtain F10.
With Range.End[IExcel.XlDirection]
property, it returns the last continuous no-empty cell in the specified direction. Note that if the Range is empty, it will return the first no-empty cell or last cell(when excel reach its boundaries) in the given direction. Ex: the whole column A is empty, Range["A1"].End[IExcel.XlDirection.xlDown]
will be A65535(last row in excel 97-2003, A1048576 for excel 2007)
//Just In case if you are wondering what IExcel is
using IExcel = Microsoft.Office.Interop.Excel;
This should get the first first and last cell of the range:
Initiate Excel.
Open workbook.
Select your range, in this case I got the used range of the active sheet.
Call the get_address method of the range.
Split the result of get_address on the colon.
The first value of the array resulting from the split will have the beginning cell.
The second value of the array resulting from the split will have the ending cell.
Replace the dollar signs with nothing and you will have the beginning and ending cells for the range.
Microsoft.Office.Interop.Excel.Application excel = new Application();
Microsoft.Office.Interop.Excel.Workbook workBook =
excel.Workbooks.Open(fileLocation);
Microsoft.Office.Interop.Excel.Worksheet sheet = workBook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
string address = range.get_Address();
string[] cells = address.Split(new char[] {':'});
string beginCell = cells[0].Replace("$", "");
string endCell = cells[1].Replace("$", "");
workBook.Close(true);
excel.Quit();
If you want the last column and last row relative to the beginning of the range you can do the following:
int lastColumn = range.Columns.Count;
int lastRow = range.Rows.Count;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With