Thursday, October 20, 2011

How to remove duplicate data with MS Excel Macro

We sometime need to have unique entry or row in MS Excel worksheet. When the data not so many we can remove duplicate data manually, but it will become problem to remove duplicate in hundreds or thousands of line/row.

Following are sample of program with macro VB (Visual Basic) to do sorting and remove duplicate data. How to run macro program can be viewed in following link  http://nisura.blogspot.com/2011/05/mengatur-supaya-huruf-pertama-kapital.html

Listing of macro VB:

Sub Sorting_Unik()
Dim i
ActiveSheet.Range("A:B").Sort Key1:=Cells(1, 1)
Start = True
i = 1
Do While Start
 s = UCase(Cells(i, 1).Value)
 t = UCase(Cells(i + 1, 1).Value)
 If s = t Then
  Duplikat = True
  Do While Duplikat
    Cells(i + 1, 1).Value = ""
    Cells(i + 1, 2).Value = ""
    i = i + 1
    t = UCase(Cells(i + 1, 1).Value)
    If s <> t Then Duplikat = False
  Loop
 End If
 If Cells(i + 2, 1).Value = "" Then Start = False
 i = i + 1
Loop
ActiveSheet.Range("A:B").Sort Key1:=Cells(1, 1)
End Sub


Basic idea of this program is to do sorting first, then compare first row with the next row, if it is unique then continue to next cell row, if it is duplicate then the next row is deleted and it will do looping till no duplicate found, then its continue to the next row until last row contain none "". Finally it will do sorting again to remove blanks row ...

The result will be like this:


MS Excel - removing duplicate data with macro program





(TangSel 20oct11)