How do I use Excel VBA to get the last cell that contains data within a specific range, such as in columns A and B Range("A:B")
?
Asked
Active
Viewed 1e+01k times
4
-
2see http://stackoverflow.com/a/8583926/641067 – brettdj Jan 09 '12 at 08:28
-
4This question has been asked a thousand times. See this link: [Ozgrid](http://www.ozgrid.com/VBA/ExcelRanges.htm) – Reafidy Jan 09 '12 at 19:52
3 Answers
8
using Find
like below is useful as it
- can find the last (or first) cell in a 2D range immediately
- testing for
Nothing
identifies a blank range - will work on a range that may not be contiguous (ie a
SpecialCells
range)
change "YourSheet"
to the name of the sheet you are searching
Sub Method2()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("YourSheet")
Set rng1 = ws.Columns("A:B").Find("*", ws.[a1], xlValues, , xlByRows, xlPrevious)
If Not rng1 Is Nothing Then
MsgBox "last cell is " & rng1.Address(0, 0)
Else
MsgBox ws.Name & " columns A:B are empty", vbCritical
End If
End Sub

brettdj
- 54,857
- 16
- 114
- 177
-
`Find` is indeed also worth noting even if this is not my favorite way :) – JMax Jan 09 '12 at 10:34
-
1
6
You can try several ways:
Using xlUp
Dim WS As Worksheet
Dim LastCellA As Range, LastCellB As Range
Dim LastCellRowNumber As Long
Set WS = Worksheets("Sheet1")
With WS
Set LastCellA = .Cells(.Rows.Count, "A").End(xlUp)
Set LastCellB = .Cells(.Rows.Count, "B").End(xlUp)
LastCellRowNumber = Application.WorksheetFunction.Max(LastCellA.Row, LastCellB.Row)
End With
Using SpecialCells
Dim WS As Worksheet
Dim LastCell As Range
Set LastCell = Range("A:B").SpecialCells(xlCellTypeLastCell)
The latter can sometimes be tricky and might not work as you wanted it to.
More tips
You can also have a look at Chip Pearson's page about this issue
0
For a variable selection you can use
Sub test()
Dim arrArray As Variant
Dim iAct As Integer
Dim iHighest As Integer
arrArray = Split(Selection.Address(1, 1, xlR1C1), ":")
For Count = Right(arrArray(0), 1) To Right(arrArray(1), 1)
iAct = ActiveSheet.Cells(Rows.Count, Count).End(xlUp).Row
If iAct > iHighest Then iHighest = iAct
Next Count
MsgBox iHighest
End Sub

DKSan
- 4,187
- 3
- 25
- 35
-
-
1Sorry, but looping to find the last cell, is just a waste of time and resources IMHO. – Reafidy Jan 09 '12 at 19:56