1

I have the following vba code:

StartLastRow = .Cells(1, 1).SpecialCells(xlLastCell).Row

If StartLastRow > 24 Then
    .Cells(StartLastRow, 1).CurrentRegion.EntireRow.Delete
    StartLastRow = .Cells(1, 1).SpecialCells(xlLastCell).Row
End If

After deleting rows the value of StartLastRow remains the same.
How can I fix it?

Community
  • 1
  • 1
genespos
  • 3,211
  • 6
  • 38
  • 70

1 Answers1

1

Following @Siddharth Rout comment above, using the Find function is the safest way to get the last row.

StartLastRow = FindLastRow

If StartLastRow > 24 Then
    .Cells(StartLastRow, 1).CurrentRegion.EntireRow.Delete
    StartLastRow = FindLastRow
End If

'=======================================================================

Function FindLastRow() As Long
    ' This Function finds the last row in a worksheet, and returns the row number
    Dim LastCell As Range
    Set LastCell = Cells.Find(What:="*", After:=Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
                        searchorder:=xlByRows, searchdirection:=xlPrevious, MatchCase:=False)
    If Not LastCell Is Nothing Then
        FindLastRow = LastCell.Row
    Else
        MsgBox "Error! worksheet is empty", vbCritical
        FindLastRow = -10000
    End If

End Function
Shai Rado
  • 33,032
  • 6
  • 29
  • 51
  • Thanks, but this is a workaround and I prefer to use another sheet (I can in this case). Anyway I appreciate (+1) – genespos Nov 29 '17 at 17:16