How to retrieve the first cell in the used range in Excel?
24 Jun 20263 minutes to read
The following code examples demonstrate retrieving the first cell in the used range of an Excel worksheet using C# (Cross-platform and Windows-specific) and VB.NET.
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Open(Path.GetFullPath(@"Data/Input.xlsx"));
IWorksheet worksheet = workbook.Worksheets[0];
//Get the used range of the worksheet
IRange usedRange = worksheet.UsedRange;
//Get the first cell from the used range
IRange firstCell = worksheet.Range[usedRange.Row, usedRange.Column];
//Get the address of the first cell
string firstCellAddress = firstCell.AddressLocal;
//Display the address of the first cell
Console.WriteLine("The address of the first used cell in used range is: " + firstCellAddress);
//Save the workbook
workbook.SaveAs(Path.GetFullPath(@"Output/Output.xlsx"));
}using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Open("Input.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
//Get the used range of the worksheet
IRange usedRange = worksheet.UsedRange;
//Get the first cell from the used range
IRange firstCell = worksheet.Range[usedRange.Row, usedRange.Column];
//Get the address of the first cell
string firstCellAddress = firstCell.AddressLocal;
//Display the address of the first cell
Console.WriteLine("The address of the first used cell in used range is: " + firstCellAddress);
//Save the workbook
workbook.SaveAs("Output.xlsx");
}Using excelEngine As New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Xlsx
Dim workbook As IWorkbook = application.Workbooks.Open("Input.xlsx")
Dim worksheet As IWorksheet = workbook.Worksheets(0)
'Get the used range of the worksheet
Dim usedRange As IRange = worksheet.UsedRange
'Get the first cell from the used range
Dim firstCell As IRange = worksheet.Range(usedRange.Row, usedRange.Column)
'Get the address of the first cell
Dim firstCellAddress As String = firstCell.AddressLocal
'Display the address of the first cell
Console.WriteLine("The address of the first used cell in used range is: " & firstCellAddress)
'Save the workbook
workbook.SaveAs("Output.xlsx")
End UsingA complete working example in C# is present on this GitHub page.