Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Conditionally Deleting Rows.

Conditionally Deleting Rows

Written by Allen Wyatt (last updated September 15, 2018)
This tip applies to Excel 97, 2000, 2002, and 2003


1

When you are working with data tables containing information that you received from another person, you may want to prune the amount of data in the table by deleting rows if a particular condition is met. There are several ways you can approach such a task.

The first method is to use Excel's AutoFilter feature. This works particularly well if you have a rather simple criteria by which to delete rows. When you turn on the AutoFilter, Excel places pull-down buttons at the right side of each cell in the data table's header row. Using these pull-down buttons you can specify the records you want displayed. You should select a filter value that will result in displaying only those rows you want to delete. With those rows displayed, you can select them and use the menus to get rid of the rows. When you turn AutoFilter off, then you are left with only the rows you wanted.

Another method involves the use of macros to do the deleting for you. This approach works well if you have to perform the deletions on lots of data, or if you do it quite often. The following macro can delete rows based on a key value:

Sub DeleteRows()
    Dim strToDelete As String
    Dim rngSrc As Range
    Dim NumRows As Integer
    Dim ThisRow As Integer
    Dim ThatRow As Integer
    Dim ThisCol As Integer
    Dim J As Integer
    Dim DeletedRows As Integer

    strToDelete = InputBox("Value to Trigger Delete?", "Delete Rows")
    Set rngSrc = ActiveSheet.Range(ActiveWindow.Selection.Address)

    NumRows = rngSrc.Rows.Count
    ThisRow = rngSrc.Row
    ThatRow = ThisRow + NumRows - 1
    ThisCol = rngSrc.Column

    For J = ThatRow To ThisRow Step -1
        If Cells(J, ThisCol) = strToDelete Then
            Rows(J).Select
            Selection.Delete Shift:=xlUp
            DeletedRows = DeletedRows + 1
        End If
    Next J
    MsgBox "Number of deleted rows: " & DeletedRows
End Sub

To use the macro, select the range the key range that covers the rows you want checked. For instance, if the key to be checked is in column G, and you want to check rows 5 through 73, then you would select the range G5:G73. When you run the macro, it asks you what value it should check for. If any cells in the range G5:G73 contain the value you specify, the corresponding row for that cell will be deleted.

There are obviously other ways to delete rows based on a value. For a good selection of different methods, take a look at this page by Dave Hawley at Ozgrid:

http://www.ozgrid.com/VBA/VBACode.htm

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (2386) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Conditionally Deleting Rows.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Making Sure Word Doesn't Capitalize Anything Automatically

Word, in an effort to be helpful, will often change the capitalization of the words you type. If you tire of Word's ...

Discover More

Placing Text in Empty Table Cells

Tables are often used to organize information into an understandable format. If your company requires that tables in ...

Discover More

Preventing Automatic Date Formatting Changes

Excel often changes the formatting of a cell based on how it parses what you are entering into that cell. This is ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (menu)

Clearing and Deleting Cells

When you want to remove information from a worksheet, you can either clear cells or delete cells. This tip examines the ...

Discover More

Quickly Deleting Cells

If you need to delete a cell, the Delete key won't do it. (That only clears the contents of a cell; it doesn't delete the ...

Discover More

Checking for Duplicate Rows Based on a Range of Columns

When working with data in Excel, you might want to figure out which rows of data represent duplicates of other rows. If ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 7 + 0?

2018-09-21 05:50:08

Thomas Papavasiliou

Using the Auto filter mode for the desired value in the relative column, then marking each matching row in an added column, sorting on the added marked column and deleting entirely all marked rows is quite fast.

Voluntarily, macro erases the rows containing the selected cell (used as criterion) downwards from the selected row

Macro works also for selected empty cell

If anyone is interested, here is the macro:
It may look quite long but the main part is fairly small. The length is due to the dialogs and controls


Option Explicit
Sub Fast_erase_on_selection()

'Macro written 15/3/2005 by xxxxx xxxxxx
'Revision 1 dated 22/11/2009

'Variable definition
Dim a_ As String
Dim ad As String
Dim ad1 As String
Dim msg As String
Dim F_ As String
Dim ttl As String
Dim c_ As Integer
Dim sc As Integer
Dim ec As Integer
Dim r_ As Long
Dim cc As Long
Dim fec As Long
Dim cec As Long
Dim sr As Long
Dim er As Long
Dim a1 As Long
Dim v_ As Variant

On Error Resume Next

'If set, reset auto-filter
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If

'Information on active cell
With ActiveCell
r_ = .Row
c_ = .Column
v_ = .Value
a_ = .Address
F_ = .NumberFormat
End With

'Error selection processing
If IsError(ActiveCell) Then
MsgBox "Selection points to an error cell. Macro stops"
Exit Sub
End If

If F_ <> "General" Then
v_ = Format(v_, F_)
End If

'Information on used range
With ActiveSheet.UsedRange
sr = .Row
sc = .Column
er = .Rows.Count + sr
ec = .Columns.Count + sc
ad = .Address
End With

'Control for a selection outside used range
'This control can be performed by the "Union" or by the "Intersect" method
'The "Intersect" method needs the "On Error Resume Next" statement
'Therefore the "Union" method is preferred and the "Intersect" method as well as the two "On Error.." statements are commented

'Union method
ad1 = Union(Range(ad), Range(a_)).Address
If ad1 <> ad Then
ttl = "Attention.... "
msg = "Attempt to run with a selection outside used range "
msg = msg & vbCr & "Macro ends!"
MsgBox msg, vbOKOnly + vbInformation, ttl
Exit Sub
End If

''''Intersect method
''' ad1 = Intersect(Range(ad), Range(a_)).Address
''' If ad1 <> a_ Then
''' ttl = "Attention.... "
''' msg = "Attempt to run with a selection outside used range "
''' msg = msg & vbCr & "Macro ends!"
''' MsgBox msg, vbOKOnly + vbInformation, ttl
''' Exit Sub
''' End If
''' On Error GoTo 0

With Application
'''' .ScreenUpdating = False
.Calculation = xlCalculationManual
End With

'Applying auto-filtering
Columns(c_).Autofilter Field:=1, Criteria1:="=" & v_, VisibleDropDown:=True

'Inserting sort and erase criterion
Range(Cells(r_, ec), Cells(er - 1, ec)) = 1

'Exiting auto-filter mode
ActiveSheet.AutoFilterMode = False

'Sorting to entered criterion
Range(a_).CurrentRegion.Sort _
key1:=Cells(1, ec), _
order1:=xlAscending, _
Header:=xlNo, _
OrderCustom:=1, _
MatchCase:=False, _
Orientation:=xlTopToBottom

'Counting the rows to erase
a1 = Columns(ec).SpecialCells(xlCellTypeConstants, 1).Count

'Erasing rows
Range(Cells(1, 1), Cells(a1, 1)).EntireRow.Delete

'Getting focus back to start point
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With

Cells.EntireRow.Hidden = False
Range(a_).Select

msg = "On this run, on active column and for the used area downwards the selection " & vbCr

If v_ = "" Then
msg = msg & "Macro erased " & a1 & " empty cell(s) row(s)"
Else
msg = msg & "Macro erased " & a1 & " cell(s) rows(s), containing: """ & v_ & """"
End If

ttl = "Thank you for using our macro."

MsgBox msg, vbOKOnly + vbInformation, ttl

End Sub



This Site

Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.