MrExcel Message Board


Go Back   MrExcel Message Board > Question Forums > Excel Questions

Excel Questions All Excel/VBA questions - formulas, macros, pivot tables, general help, etc. Please post to this forum in English only.

Reply
 
Thread Tools Display Modes
Old May 31st, 2002, 05:55 PM   #1
rayfarag
 
Join Date: May 2002
Posts: 1
Default

How can you write a macro to delete duplicate records in an excel file with over 2000 records?
rayfarag is offline   Reply With Quote
Old May 31st, 2002, 06:44 PM   #2
Damon Ostrander
MrExcel MVP
 
Damon Ostrander's Avatar
 
Join Date: Feb 2002
Location: Denver, Colorado USA
Posts: 3,876
Default

Hi rayfarag,

Here is a simple macro that does this. This assumes that a "duplicate record" is a row whose cells ALL match the cells of a previous row. Just select all the rows you want duplicate records delete from and run the macro.

Sub DelDups()

' Deletes duplicate rows in the selected range.
' All columns in the selected range must be identical for
' a row to be deleted. The entire row, not just the selected
' cells in the row, will be deleted if a duplicate is found.
' The first instance of the duplicate row is the copy that
' will be retained.

Dim iRow As Long
Dim jRow As Long
Dim iCol As Integer
Dim LastRow As Long 'The last row in the selected range
Dim FirstRow As Long 'The first row in the selected range
Dim FirstCol As Integer
Dim LastCol As Integer
Dim DelCount As Long 'The count of duplicate rows removed
Dim DupFound As Boolean 'True if duplicate row found

DelCount = 0

FirstRow = Selection.Row
LastRow = FirstRow + Selection.Rows.Count - 1
FirstCol = Selection.Column
LastCol = FirstCol + Selection.Columns.Count - 1

For iRow = FirstRow To LastRow - 1

For jRow = iRow + 1 To LastRow

DupFound = True
For iCol = FirstCol To LastCol
DupFound = DupFound And (Cells(jRow, iCol) = Cells(iRow, iCol))
If Not DupFound Then Exit For
Next iCol
If DupFound Then
' Duplicate row found--delete it
Rows(jRow).Delete
LastRow = LastRow - 1
DelCount = DelCount + 1
End If

Next jRow

Next iRow

Beep
MsgBox DelCount & " duplicate rows deleted.", _
vbInformation, "Duplicate Removal Results"

End Sub

Keep Excelling.

Damon

PS. If this is not what you meant by duplicate record, let me know. It is even easier to delete records based on duplicate values in just one column.
Damon Ostrander is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On

Forum Jump


All times are GMT +1. The time now is 10:42 AM.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
All contents Copyright 1998-2009 by MrExcel Consulting.