The Last Row
- To get the last row in a column i.e. the row of the last non-empty cell, you want to make sure that the worksheet is not filtered. Then you can freely use the
Find
method in the way illustrated in the following codes.
- If you want to find the last non-blank row e.g. you want to exclude cells containing formulas evaluating to
""
at the bottom of your data, you will use xlValues
instead of xlFormulas
.
xlFormulas
will work even if rows are hidden (not filtered) while xlValues
will not.
A Quick Fix (Not Recommended)
lrow = Worksheets("Sheet1").Columns("A").Find("*", , xlFormulas, , , xlPrevious).Row
Last Row
Sub CalculateLastRow()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
If ws.FilterMode Then ws.ShowAllData
Dim lRow As Long
With ws.Range("A2")
Dim lCell As Range: Set lCell = .Resize(ws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If Not lCell Is Nothing Then lRow = lCell.Row
End With
If lRow = 0 Then
Debug.Print "No data found."
Else
Debug.Print "The last row is row " & lRow & "."
End If
End Sub
Range (more useful)
Sub ReferenceRange()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
If ws.FilterMode Then ws.ShowAllData
Dim rg As Range
With ws.Range("A2")
Dim lCell As Range: Set lCell = .Resize(ws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If Not lCell Is Nothing Then Set rg = .Resize(lCell.Row - .Row + 1)
End With
If rg Is Nothing Then
Debug.Print "No data found."
Else
Debug.Print rg.Address(0, 0)
End If
End Sub
Q&A
Q: What does the following mean?
With ws.Range("A2")
Set ... = .Resize(ws.Rows.Count - .Row + 1)
End With
A: It's a way to reference the range A2:A1048576
(A2:A65536
in older
versions), the range to be searched in.
Q: What does the following mean?
.Find("*", , xlFormulas, , , xlPrevious)
A: It means that there are only 3 arguments necessary for this operation: 1st - What
, 3th - LookIn
, and 6th - SearchDirection
. The default parameter of the 2nd argument, After
, is the first cell of the range (in this case A2
), the 4th argument, LookAt
, is irrelevant since we're using a wild card, while the 5th argument, SearchOrder
is irrelevant when performing this operation in a single column or single row. The last 3 arguments (from a total of 9) aren't worth mentioning.