Search code examples
duplicatesdelete-row

Removing duplicates with VBA removes more than just duplicates


I'm trying to to create a code that will add new lines to a table and then removes duplicates based on information from one of the columns in that table. I'm not very proficient in using VBA so most of my codes are recorded and adjusted.

My problem here is that once the code reach the "Remove duplicate" part it removes more than just duplicates i.e. I have originally 20 records, I add 10 more out of which 5 are duplicates, so as an end result I should be left with 25 Original lines, unfortunately my code removes more and instead of 25 expected lines I end up with having only 17, so less than original amount!

I would appreciate if you could help me understand why this is happening and how this can be fixed.

Sub Add_New_Orders()
Add_New_Orders Macro

Sheets("Source1_DateRange").Select
Range("DateRange[[Customer]:[Order No]]").Select
Selection.Copy
Sheets("Overview").Select
Range("B7").Select
Selection.End(xlDown).Offset(1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Application.CutCopyMode = False
ActiveSheet.Range("Overview[#All]").RemoveDuplicates Columns:=Array(3), Header:= _
    xlYes  ' I also tried to use Columns"=Column(3) with same result
    
End Sub

Solution

  • I have managed to find a solution myself. Not sure how it happened but it works now as expected. I have added 2 lines to the code and it somehow fixed the issue for me. I do believe that because I did not select/specify the column from which I tried to remove duplicates, code was searching for all duplicates within my table and not only in Column 3.

    Sub Add_New_Orders
    Sheets("Source1_DateRange").Select
    Range("DateRange[[Customer]:[Order No]]").Select
    Selection.Copy
    Sheets("Overview").Select
    Range("B7").Select
    Selection.End(xlDown).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    Range("Overview[[#All],[Order no]]").Select ' NEW ADDED LINE
    Range("C9").Activate ' NEW ADDED LINE
    ActiveSheet.Range("Overview[#All]").RemoveDuplicates Columns:=3, Header:= _
        xlYes
        
    

    End Sub