Home » excel » vba – Excel Macro Loop – removing duplicates per column

vba – Excel Macro Loop – removing duplicates per column

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am new to excel macros and would like to create loop that identified a column range and hopefully a row range to remove duplicates. Currently I have taken the long way around that created an excel formula to create the macro script for the below.

Any help with the below would be much appreciated cause I am now at 60 columns and need to add another 40…

Thank you

Sheets("Result").Select
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$100000").RemoveDuplicates Columns:=1, Header:=xlNo
Columns("B:B").Select
ActiveSheet.Range("$B$1:$B$100000").RemoveDuplicates Columns:=1, Header:=xlNo
Columns("C:C").Select
ActiveSheet.Range("$C$1:$C$100000").RemoveDuplicates Columns:=1, Header:=xlNo
Columns("D:D").Select
ActiveSheet.Range("$D$1:$D$100000").RemoveDuplicates Columns:=1, Header:=xlNo
Columns("E:E").Select
ActiveSheet.Range("$E$1:$E$100000").RemoveDuplicates Columns:=1, Header:=xlNo
Columns("F:F").Select
ActiveSheet.Range("$F$1:$F$100000").RemoveDuplicates Columns:=1, Header:=xlNo
How to&Answers:

This will work if you only care about duplicates per column.

Sub RemoveDuplicates()
    'Stop the screen from updating to reduce lag
    Application.ScreenUpdating = False

    'Main loop
    For i = 1 To 100
        ActiveWorkbook.Sheets("Result").Columns(i).RemoveDuplicates Columns:=1, Header:=xlNo
    Next

    'Reset ScreenUpdating
    Application.ScreenUpdating = True
End Sub

Answer:

This will perform a column-by-column duplicate removal:

Sub Kleanup()
    For i = 1 To Columns.Count
        Columns(i).Cells.RemoveDuplicates Columns:=1, Header:=xlNo
    Next i
End Sub

Answer:

You need a loop!

Sub RemoveDuplicates()
    Dim TargetSheet As Worksheet
    Set TargetSheet = ActiveWorkbook.Worksheets("Result")
    For i = 1 To 100
        TargetSheet.Cells(1, i).EntireColumn.RemoveDuplicates Columns:=1, Header:=xlNo
    Next i
End Sub