Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: How to delete filtered rows in Excel?

I have an Excel table that contains some data. By using next vba code I'm trying to filter only blank cells in some fields and delete these rows

ActiveSheet.Range("$A$1:$I$" & lines).AutoFilter Field:=7, Criteria1:= _
        "="
ActiveSheet.Range("$A$1:$I$" & lines).AutoFilter Field:=8, Criteria1:= _
        "="
ActiveSheet.Range("$A$1:$I$" & lines).AutoFilter Field:=9, Criteria1:= _
        "="
ActiveSheet.UsedRange.Offset(1, 0).Resize(ActiveSheet.UsedRange.rows.Count - 1).rows.Delete
ActiveSheet.ShowAllData

It works only if I have blank cells in this columns. But I faced with a problem, when I do not have blank cells, and by using above code all my range is removing from the sheet. How to avoid this issue? Should I change my filter condition or something else?

like image 630
mbigun Avatar asked Jun 19 '13 14:06

mbigun


People also ask

How do I delete only filtered rows in Excel VBA?

Sure, it's possible to do this quite easily using Excel's built-in menus >> select data, set auto-filter, apply filter criteria, select rows to delete, go to special “visible cells only”, delete, reset the filter to show remaining records…

How do I remove rows from filters in Excel?

Go to the Data tab in Excel and click on the Filter icon. Click on the small arrow next to the needed column name, go to Filter by Color and pick the correct cell color. Click OK and see all highlighted cells on top. Select the filtered colored cells, right-click on them and pick the Delete Row option from the menu.

How do you delete selected rows in Excel VBA?

Normally in an Excel worksheet, we have two different methods to delete rows: the keyboard shortcut and the right-click and insert method. But in VBA, we must use the “Delete” command and worksheet statement to delete any rows.


2 Answers

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete
like image 190
Jon Crowell Avatar answered Sep 30 '22 02:09

Jon Crowell


As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.

ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)

As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().

like image 20
KeyLimePy Avatar answered Sep 30 '22 02:09

KeyLimePy