To find the last row in Excel VBA, you can use the following code:
Dim lastRow As Long
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
This code uses the Cells
property and the End
method to determine the last cell in column A that contains data. The xlUp
is the direction parameter used with the End
method, which means it will go up from the active cell until it finds the first non-empty cell. Finally, we get the row number of the last cell to get the last row.
Here’s an example to illustrate the usage:
Sub FindLastRowExample()
Dim lastRow As Long
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox "The last row is: " & lastRow
End Sub
In this example, the code will find the last row in column A of the active sheet and display it in a message box.