简体   繁体   中英

Remove Duplicates using vba

I want to delete duplicate entries from each column, I am successful in doing it for one column C but I want to do it from A to Column Z. I have tried to change myCol to variable long & wrote column number but it is giving me an error (so that I can run number loop). Here is my code:

Sub test()
Dim myCol As String

myCol = "C"

With Sheets("Union")
    lastrow = .Range(myCol & .Rows.Count).End(xlUp).Row
    .Range(myCol & "1:" & myCol & lastrow).RemoveDuplicates Columns:=1, Header:=xlYes
End With

End Sub

You could try creating a For loop accounting for AZ as integers. I am not sure that this is the most efficient solution, but it could work for you. See below.

Option Explicit

Sub test()

    Dim myCol As Long
    Dim lastrow As Long

    For myCol = 1 To 26
        With Sheets("Union")
            lastrow = .Cells(.Rows.Count, myCol).End(xlUp).Row

            If lastrow >= 3 Then
                .Range(.Cells(1, myCol), .Cells(lastrow, myCol)).RemoveDuplicates Columns:=1, Header:=xlYes
            End If
        End With
    Next myCol

End Sub

EDIT : Tested, and working as required.

SECOND EDIT : Added in a lastrow check to ensure there is some data in the column before trying to remove duplicates. 3 because that would mean at least 2 entries in that column, the minimum for there to be a need to check for duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM