Search code examples
excelfilterdelete-rowworksheet-functionvba

Excel VBA Macro: incorporating filters and using a macro to delete visible and subsequent empty rows


I have a spreadsheet with ~50,000 rows of data. This value will fluctuate because I have a function to bring in more data.

What I am hoping to do is be able to use my column filters (Row 2) to display the items I do not want. Then the macro will delete all the visible values, turn off the filters, delete all the empty rows, and finally turn the filters in row 2 back on. The following code is designed to do this but leaves empty rows throughout the data matrix. Thank you for your help!

Sub DeleteVisible_Empty_BlankRows()
  Application.ScreenUpdating = False
  Range("C3:V" & rows.count).ClearContents
  Worksheets("MyDataPull").AutoFilterMode = False

'Ungroup & regroup necessary columns
  Columns("F:K").Columns.Ungroup

  Dim r As Range, emrows As Long, i As Long
  LRI = Mydatapull.Cells(Mydatapull.rows.count, "C").End(xlUp).Row

'Filter column C from A to Z so that blanks are put at the bottom
  Range("C3:V" & LRI).Sort Key1:=Range("C3"), Order1:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

'Filter to only show blanks
  Range("C3:V" & LRI).AutoFilter Field:=1, Criteria1:="=", Operator:=xlOr, Criteria2:="=" & ""

'Delete blanks
  Range("C3:V" & LRI).EntireRow.Delete

'Turn filters back on
  Worksheets("MyDataPull").AutoFilterMode = False

'Delete Extra rows
  LRI = Mydatapull.Cells(Mydatapull.rows.count, "C").End(xlUp).Row
  Range("C" & LRI + 1 & ":V" & rows.count).EntireRow.Delete

  Mydatapull.Range("C2:V2").AutoFilter
  Columns("F:K").Columns.Group

End Sub

Solution

  • I figured this out. See the updated code above.