简体   繁体   中英

How do I reference a stored range to remove duplicates in Excel VBA

I have a couple of Excel sheets with between almost 200 to just over 500 rows containing duplicate values, which I need to remove. Since the number of rows varies quite a lot I need to get the function for removing the duplicates to use a dynamic range in some way. The solution I'm trying to use is:

Sub RemoveDup()

    Dim SR as Range

    Range(Cells(2,1), Selection.End(xlDown)).Select

    Set SR = Selection

    ActiveSheet.Range(SR).RemoveDuplicates Columns:=1, Header:=xlNo 'This doesn't work.

End Sub

The range-reference in my last statement doesn't work. I've tried to place it between " with and without &. But that didn't seem to be the trick either.

How should I reference to my stored range?

You could try the following, this will get the Last Row with data in Column A, and then use that range to remove duplicates:

Sub RemoveDup()
    SR = Cells(Rows.Count, "A").End(xlUp).Row
    'get the last row with data on Column A

    Range("A2:A" & SR).RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

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