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
Microsoft 365 and Office | Development | Other
Building custom solutions that extend, automate, and integrate Microsoft 365 apps.
Microsoft 365 and Office | Excel | For business | Windows
Microsoft 365 and Office | Excel | For business | Windows
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data
Sign in to answer