Excel VBA: get the last cell containing data in the selected range

How to use Excel VBA to get the last cell containing data in a certain range, for example, columns A and B Range("A:B")?

+5
source share
3 answers

using Findas shown below is useful

  • can immediately find the last (or first) cell in the 2D range
  • testing Nothingmeans a space
  • will work in a range that cannot be adjacent (i.e. a range SpecialCells)

change "YourSheet"to the name of the sheet you are looking for

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
+8
source

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)

, .

Chip Pearson

+6

To select a variable 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
0
source

All Articles