Home » excel » VBA Excel Clearing

VBA Excel Clearing

Posted by: admin May 14, 2020 Leave a comment


The following code works but runs too slowly on large files, so the code needs to be modified to identify the first year that is earlier than 2019 and then delete that row and the row containing the rest of the years below that, all at one time:

  Do Until ActiveCell.Value =""
    If ActiveCell.Value < 2019 Then
End If

Code Problem: data sets can have 1000’s of rows so checking every cell is very slow. Since the data is always in order, all I need to do is find the first entry <2019 and then select xldown and delete everything, but I don’t know how to find that cell and make it the active cell.

How to&Answers:

as stated in the comments:

Dim firstrow As Variant
firstrow = Application.Match(2018, ActiveSheet.Range("B:B"), -1)

If Not IsError(firstrow) Then
    Dim lastrow As Long
    lastrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 2).End(xlUp).Row

    ActiveSheet.Rows(firstrow + 1 & ":" & lastrow).Delete
End If