0

I'm stumped on this one and haven't been able to find the answer through search.

This comes from the macro-recorder when I remove duplicates from the last 3 columns of my range.

Sub Macro1()
' Macro1 Macro
    Range("A1:E8").Select
    Application.CutCopyMode = False
    ActiveSheet.Range("$A$1:$E$8").RemoveDuplicates _
        Columns:=Array(3, 4, 5), Header:=xlYes
End Sub

I want to make a macro that does this using variables instead of Array(3, 4, 5) but I get an error when trying to pass an array built from variables.

Sub MyTry1()
    Dim iArray() As Integer, i As Integer
    With ActiveSheet.Range("$A$1:$E$8")
        ReDim iArray(1 To .Columns.Count - 2)
        For i = 1 To 3
            iArray(i) = i + 2
        Next i  'Result is iArray= (3, 4, 5)      
        .RemoveDuplicates Columns:=iArray, Header:=xlYes
       'returns Run-time error "5": Invalid procedure call or argument
    End With
End Sub

I've tried Integer, Long and Variant data types, but no luck.

1 Answer 1

2

You can use a zero-based Variant Array of Integers and wrap the Array Reference in parentheses as shown below

Sub MyTry2()
    Dim iArray As Variant, i As Integer
    Dim rData As Range
    Set rData = Range("$A$1:$E$8")
    With rData
        ReDim iArray(0 To .Columns.Count - 3)
        For i = 0 To UBound(iArray)
            iArray(i) = i + 3
        Next i
        .RemoveDuplicates Columns:=(iArray), Header:=xlYes
    End With
End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.