VBA course · Lesson 23 of 33
Find the last row and build dynamic ranges in VBA
Find the last used row and column reliably with End(xlUp), CurrentRegion and Find, avoid UsedRange traps, and build ranges that grow with your data.
A macro that works on A2:F500 breaks the day your list reaches row 501, and it wastes time on empty rows while the list is still at row 40. Real data grows and shrinks every week: new invoices arrive, staff leave, exports have a different length each month. Almost every practical macro therefore starts with the same question: where does my data end?
This lesson shows the common ways to answer that question, when each one goes wrong, and how to turn the answer into a range of exactly the right size with Resize and Offset. At the end you will have a small, reusable LastRow function that you can paste into every project. You should know how Range and Cells work (Range and Cells: working with cells in VBA) before you start.
We use this sales list on a sheet named Sales:
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Date | Rep | Region | Amount |
| 2 | 02-Nov-2026 | Ana | North | 1200 |
| 3 | 04-Nov-2026 | Ben | South | 860 |
| 4 | 09-Nov-2026 | Ana | North | |
| 5 | 13-Nov-2026 | Chloe | East | 2150 |
| 6 | 18-Nov-2026 | Ben | South | 940 |
| 7 | 25-Nov-2026 | Dev | West | 1310 |
Sales sheet: data in A1:D7, a note far away in H20 (not shown)
Notice the empty amount in D4 and imagine someone has typed a note in H20. Both are deliberate: they are exactly the kind of thing that breaks naive "last row" code.
Method 1: End(xlUp) from the bottom of the sheet
This is the method you will use most. It is the code version of selecting the very last cell of a column and pressing Ctrl+Up arrow (Mac: Cmd+Up arrow): Excel jumps upwards to the first non-empty cell.
Option Explicit
Sub ShowLastRow()
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Worksheets("Sales")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
MsgBox "The last row with a date is " & lastRow ' shows 7
End Subws.Rows.Count is the number of rows on the sheet, 1,048,576 in modern Excel and 65,536 in old .xls files. Using the property instead of typing the number keeps the code correct for both. Cells(ws.Rows.Count, "A") is the bottom cell of column A, .End(xlUp) jumps to the last filled cell above it, and .Row gives its row number.
Why start from the bottom instead of jumping down from A1 with End(xlDown)? Because End(xlDown) stops at the first gap. In our list, jumping down column D from D1 stops at D3, because D4 is empty. Jumping up from the bottom ignores gaps above the last value.
End(xlUp) in column D returns 7 here, but if the last sale had no amount yet it would return a row too early. Use a column that is always filled, such as a date, an ID or an invoice number.The variable must be a Long, not an Integer. An Integer stops at 32,767 and causes an overflow error on large sheets (Variables and data types: Dim, Option Explicit and scope).
The last column: End(xlToLeft)
The same idea works sideways. Start at the far right of a row and jump left:
Sub ShowLastColumn()
Dim ws As Worksheet
Dim lastCol As Long
Set ws = ThisWorkbook.Worksheets("Sales")
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
MsgBox "Headers end in column " & lastCol & _
" (" & Split(ws.Cells(1, lastCol).Address(True, False), "$")(0) & ")"
End SubThis shows column 4 (D). The Split trick turns the address D$1 into the letter D, which is handy for messages.
The empty-sheet trap
On an empty sheet, End(xlUp) from the bottom stops at row 1 even though row 1 is empty, so the "last row" is 1. If your code then writes to lastRow + 1, the first record lands in row 2 and row 1 stays blank, which is usually what you want for a header. But if you read from row 2 to the last row, a loop For r = 2 To 1 simply does not run, which is also fine. Problems appear when you build a range like Range("A2:D" & lastRow) and lastRow is 1: you get A2:D1, which Excel silently turns into A1:D2, including the header. Always check:
If lastRow < 2 Then
MsgBox "There is no data below the headers."
Exit Sub
End IfMethod 2: CurrentRegion
CurrentRegion is the block of filled cells around a starting cell, bounded by completely empty rows and columns. It is the same as selecting a cell and pressing Ctrl+A (Cmd+A) once, or Ctrl+Shift+8.
Sub ShowCurrentRegion()
Dim data As Range
Set data = ThisWorkbook.Worksheets("Sales").Range("A1").CurrentRegion
MsgBox data.Address & " has " & data.Rows.Count & " rows" ' $A$1:$D$7, 7 rows
End SubCurrentRegion is ideal for clean lists with a header and no fully empty row or column inside. The single empty cell in D4 does not break it, because the row still contains other values. A completely empty row would cut the region in two, and the note in H20 is ignored because it does not touch the block. That makes it a good fit for Find, filter and sort data with VBA, where AutoFilter and Sort want exactly the list.
Method 3: UsedRange and why to be careful with it
ws.UsedRange is the rectangle from the first to the last cell that Excel thinks has been used. It sounds perfect, but:
- It includes cells that only have formatting, such as a border someone drew in row 900.
- It does not always shrink after you delete data; Excel resets it only when the file is saved or the property is read in some versions.
- It does not have to start at A1. If the sheet starts at B3,
UsedRange.Rows.Countis not the last row number.
With the note in H20, UsedRange is A1:H20, which is clearly not the list. If you must use it, compute the last row correctly:
Sub UsedRangeLastRow()
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Worksheets("Sales")
With ws.UsedRange
lastRow = .Row + .Rows.Count - 1
End With
MsgBox "UsedRange ends in row " & lastRow ' 20 because of the note in H20
End SubMethod 4: Find("*") for the true last cell
When you need the last row that contains anything in any column, and you do not want formatting to count, search backwards for "any value" with Find:
Sub TrueLastCell()
Dim ws As Worksheet
Dim lastCell As Range
Dim lastRow As Long
Dim lastCol As Long
Set ws = ThisWorkbook.Worksheets("Sales")
Set lastCell = ws.Cells.Find(What:="*", After:=ws.Range("A1"), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If lastCell Is Nothing Then
MsgBox "The sheet is empty."
Exit Sub
End If
lastRow = lastCell.Row
lastCol = ws.Cells.Find(What:="*", After:=ws.Range("A1"), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
MsgBox "Last row " & lastRow & ", last column " & lastCol ' 20 and 8
End SubStarting "after" A1 and searching backwards means the search wraps to the very last cell of the sheet and moves up from there. xlByRows finds the last row, xlByColumns the last column. LookIn:=xlFormulas also finds formulas that return an empty string, which xlValues would skip. Unlike End(xlUp), this method returns Nothing on an empty sheet, so you get a clear signal. It also sees cells in hidden rows, which End(xlUp) can skip in a filtered list.
Which method when?
| Situation | Best method |
|---|---|
| A list with one column that is always filled | End(xlUp) on that column |
| A clean block with headers, used for filter or sort | CurrentRegion |
| Any value anywhere on the sheet, ignoring formatting | Find("*", SearchDirection:=xlPrevious) |
| Data is an Excel table | ListObject.DataBodyRange (Excel tables in VBA: working with ListObjects) |
| A quick look while debugging | UsedRange, with care |
Building dynamic ranges with Resize and Offset
Once you know where the data ends, you build ranges from it. Two methods do most of the work:
Offset(rows, cols)moves a range without changing its size.Resize(rows, cols)keeps the top-left corner and changes the size.
Sub DynamicRanges()
Dim ws As Worksheet
Dim data As Range
Dim body As Range
Dim amounts As Range
Set ws = ThisWorkbook.Worksheets("Sales")
Set data = ws.Range("A1").CurrentRegion ' A1:D7
' Move down one row, then make it one row shorter: A2:D7
Set body = data.Offset(1, 0).Resize(data.Rows.Count - 1)
' Fourth column of the body: D2:D7
Set amounts = body.Columns(4)
MsgBox "Total sales: " & Format(Application.WorksheetFunction.Sum(amounts), "#,##0")
End SubThe message shows 6,460 (1,200 + 860 + 2,150 + 940 + 1,310; the empty D4 counts as nothing). Resize with only one argument keeps the number of columns. The Offset(1, 0).Resize(...) pattern, "skip the header, then trim one row", is worth learning by heart.
Appending a new row
Adding a record means writing to the row after the last one:
Sub AddSale()
Dim ws As Worksheet
Dim newRow As Long
Set ws = ThisWorkbook.Worksheets("Sales")
newRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
ws.Cells(newRow, "A").Resize(1, 4).Value = _
Array(DateSerial(2026, 11, 30), "Chloe", "East", 1780)
ws.Cells(newRow, "A").NumberFormat = "dd-mmm-yyyy"
End SubResize(1, 4) turns the single cell into one row of four cells, and an Array of four values fills them in one write, faster than four separate assignments.
| A | B | C | D | |
|---|---|---|---|---|
| 6 | 18-Nov-2026 | Ben | South | 940 |
| 7 | 25-Nov-2026 | Dev | West | 1310 |
| 8 | 30-Nov-2026 | Chloe | East | 1780 |
Rows 6 to 8 after AddSale: the new sale lands in row 8
Rows 1 to 7 are unchanged; only row 8 is new.
A reusable LastRow function
Rather than writing the same line in every macro, put it in a function in a standard module (Functions and Subs: parameters, ByVal, ByRef and return values):
Public Function LastRow(ByVal ws As Worksheet, Optional ByVal col As Variant) As Long
' With a column: last filled row in that column (0 if the column is empty).
' Without a column: last row with any value on the sheet (0 if the sheet is empty).
Dim found As Range
If IsMissing(col) Then
Set found = ws.Cells.Find(What:="*", After:=ws.Range("A1"), _
LookIn:=xlFormulas, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If found Is Nothing Then LastRow = 0 Else LastRow = found.Row
Else
LastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
If LastRow = 1 And IsEmpty(ws.Cells(1, col).Value) Then LastRow = 0
End If
End Function
Sub TestLastRow()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sales")
Debug.Print LastRow(ws, "A") ' 7
Debug.Print LastRow(ws, 4) ' 7, a column number works too
Debug.Print LastRow(ws) ' 20, because of the note in H20
End SubReturning 0 for "nothing there" makes the empty case easy to test (If LastRow(ws, "A") < 2 Then ...). The Optional ... As Variant parameter with IsMissing lets one function serve both uses.
Common mistakes
- Declaring the row as
Integer: overflow above 32,767 rows. - Using
End(xlDown)from the header, which stops at the first gap. - Hard-coding
1048576instead ofws.Rows.Count. - Forgetting the sheet:
Cells(Rows.Count, 1)withoutws.uses whichever sheet is active, which may be a different one from the sheet you meant. - Trusting
UsedRangeafter deleting rows or when stray formatting exists. - Not handling a sheet with headers only, so
A2:D1quietly becomesA1:D2.
Check yourself
1. Why do we usually start at the bottom and use End(xlUp) instead of End(xlDown) from A1?
Jumping up from the bottom ignores gaps above the last value.
2. What is the best data type for a row number?
An Integer overflows above 32,767; sheets have over a million rows.
3. Which method can be fooled by a cell that only has a border far below the data?
UsedRange includes formatted cells; Find("*") looks for content only.
4. data is A1:D7. What is data.Offset(1, 0).Resize(data.Rows.Count - 1)?
Offset moves it to A2:D8, then Resize trims it to 6 rows: A2:D7.
5. On a completely empty sheet, what does ws.Cells.Find("*", SearchDirection:=xlPrevious) return?
Find returns Nothing when no cell has content, which makes the empty case easy to detect.