How to locate the last row in Excel with filtering, using vba

Randy Street 0 Reputation points
2023-12-20T02:09:08.8+00:00

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 | Excel | For business | Windows
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.