Question posted 2014 · +7 upvotes
I was just wondering if you could help me better understand what .Cells(.Rows.Count,"A").End(xlUp).row does. I understand the portion before the .End part.
Accepted answer +18 upvotes
It is used to find the how many rows contain data in a worksheet that contains data in the column “A”. The full usage is
lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block
With ws
lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
ws.Rows.Countreturns the total count of rows in the worksheet (1048576 in Excel 2010)..Cells(.Rows.Count, "A")returns the bottom most cell in column “A” in the worksheet
Then there is the End method. The documentation is ambiguous as to what it does.
Returns a Range object that represents the cell at the end of the region that contains the source range
Particularly it doesn’t define what a “region” is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don’t use it like that:
- If the range is multiple cells, it will use the region of
rng.cells(1,1). - If the range isn’t in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
- If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.
So Range.End is not a trivial function.
.rowreturns the row index of that cell.
2 code variants in this answer
- Variant 1 — 1 lines, starts with
lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row - Variant 2 — 3 lines, starts with
With ws
Excel VBA objects referenced (5)
Range— Refer to Cells by Using a Range ObjectRange— Delete Duplicate Entries in a RangeRows.Count— Count function (Microsoft Access SQL)Rows.Count— Count the number of records in a DAO RecordsetWorksheet— Refer to All the Cells on the Worksheet
Top excel-vba Q&A (6)
- How to clear the entire array? +58 (2010)
- How to change Format of a Cell to Text using VBA +55 (2011)
- Download attachment from Outlook and Open in Excel +43 (2012)
- Can a VBA function in Excel return a range? +36 (2009)
- 2 Dimensional array from range +34 (2013)
- Hiding an Excel worksheet with VBA +33 (2009)
excel-vba solutions on this site
— top 15%.