Here is the corrected code.
Sub MyCode()
Dim Rng As Range
With ActiveSheet
Set Rng = .Cells(.Rows.Count, "A").End(xlUp)
MsgBox Rng.Row
End With
End Sub
To understand this code you need to know the syntax for defining a cell.
Set MyCell = Cells([Row number], [Column number or ID])
In the above code .Rows.Count
is a large number (1048576 to be exact). .Cells(.Rows.Count, "A")
defines the cell A1048576. Now, from there you look for the "End" going "xlUp" and arrive at the last used cell in the column.
You would use exactly the same method to find the last used cell horizontally, like Cells(2, Columns.Count).End(xlToLeft)
. Here the sheet isn't specified and therefore the ActiveSheet
by default.
Observe the double reference to ActiveSheet in .Cells(.Rows.Count, "A") as indicated by the leading periods. Both the Rows.Count and the cell itself must be in the same sheet.
Since the code explained here defines a cell, and since a range is defined by its first and last cells, you can define a range in column A as shown below.
Sub MyCode2()
Dim Rng As Range
With ActiveSheet
Set Rng = .Range(.Cells(30, 1), .Cells(.Rows.Count, "A").End(xlUp))
End With
MsgBox Rng.Address(0, 0)
End Sub