How to locate the last row in Excel with filtering, using vba
Randy Street
0
Reputation points
I have a code that locates the last row of data in an Excel worksheet and inserts a subtotal formula of a column. The code works great! Until I filter the data. Then the code does not seem to be able to locate the last row of data on the screen.
Can anyone see what might be wrong or maybe provide a suggestion on how to get this code to apply when data is filtered?
Any assistance will be greatly appreciated.
Here is my code:
Private Sub LastRow_Click()
Dim nRow As Long, nColumn As Long, LastRow As Long
nRow = Cells(Rows.Count, "A").End(xlUp).Row
nColumn = Cells(nRow, Columns.Count).End(xlToLeft).Column
If ActiveSheet.ProtectContents = True Then
ActiveSheet.Unprotect Password:="2468"
LastRow = Range(Cells(nRow, "A"), Cells(nRow, nColumn)).Select
Selection.Offset(3, 5).Select
ActiveCell.Formula = "=SUBTOTAL(9,R3C:R[-1]C)"
ActiveSheet.LockSheet.Visible = False
ActiveSheet.UnlockSheet.Visible = True
ActiveSheet.Protect Password:="2468", DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowFiltering:=True
Else
LastRow = Range(Cells(nRow, "A"), Cells(nRow, nColumn)).Select
Selection.Offset(3, 5).Select
ActiveCell.Formula = "=SUBTOTAL(9,R3C:R[-1]C)"
End If
End Sub
Microsoft 365 and Office | Development | Other
4,375 questions
Microsoft 365 and Office | Excel | For business | Windows
3,893 questions
Sign in to answer