Home » excel » excel – Remove duplicates in a variable number of columns

excel – Remove duplicates in a variable number of columns

Posted by: admin May 14, 2020 Leave a comment


I have the following code which removes duplicates from exactly 3 columns.

Sub RemoveDuplicates()
' RemoveDuplicates Macro
' Keyboard Shortcut: Ctrl+Shift+Q

    Intersect(Selection.EntireColumn, ActiveSheet.UsedRange).RemoveDuplicates _
        Columns:=Array(1,2,3), _

End Sub

The problem is in the Array(1, 2, 3) – I want the number of columns to match Selection.Columns.Count, i.e. if there is 1 column it is Array(1) or if there are 4 columns it is Array(1, 2, 3, 4), so I need to be able to build this dynamically.

I’ve tried building an Array of Longs, copying this into a Variant, and doing a Split(Join(...)), but passing any of these into the method gives me an error:

Run-time error  '5':
Invalid procedure call or argument

Using the Array() function seems to be the only valid argument, but I can’t build this dynamically.

How to&Answers:

The column array needs to be passed byval and not byref.

use ( arrCols ) not arrCols

Sub Test()

    Dim rng         As Range
    Dim lCtr        As Long

    Dim arrCols()
    Dim arrTemp

    Set rng = Sheet2.Range("A1:C11")
    arrTemp = Split("1,2", ",")

    ReDim arrCols(0 To UBound(arrTemp))

    For lCtr = LBound(arrTemp) To UBound(arrTemp)
        arrCols(lCtr) = arrTemp(lCtr)

    '/ VBA needs the array to be passed by value. Use (arrCols), notice the parenthesis!
    rng.RemoveDuplicates Columns:=(arrCols), Header:=xlYes

End Sub