VBA:使用变量传递列数组时删除重复项失败

时间:2022-12-20 04:45:15

When the Columns parameter of the RemoveDuplicates is passed using a variable it fails and throws error. Same code works when the columns are passed directly as Array(1,2)

使用变量传递RemoveDuplicates的Columns参数时,它会失败并抛出错误。当列直接作为数组(1,2)传递时,相同的代码有效

Error 5: Invalid procedure call or argument

错误5:无效的过程调用或参数

 Sub test()

       Dim arrCols

       arrCols = Array(1, 2)

       '/This here works       
       Sheet1.Range("$A$1:$B$10").RemoveDuplicates Columns:=Array(1, 2), Header _
            :=xlYes

       '/ Same code fails when the columns array is passed via variable
       '/ Error 5: Invalid procedure call or argument
        Sheet1.Range("$A$1:$B$10").RemoveDuplicates Columns:=arrCols, Header _
            :=xlYes

 End Sub

1 个解决方案

#1


4  

Put () around the array:

在数组周围放置():

Sub test()

       Dim arrCols As Variant

       arrCols = Array(1, 2)

       '/This here works
       Sheet1.Range("$A$1:$B$10").RemoveDuplicates Columns:=Array(1, 2), Header _
            :=xlYes

       '/ Same code fails when the columns array is passed via variable
       '/ Error 5: Invalid procedure call or argument
        Sheet1.Range("$A$1:$B$10").RemoveDuplicates Columns:=(arrCols), Header _
            :=xlYes

 End Sub

It has to do with what vba is expecting to see.

它与vba期待看到的有关。

#1


4  

Put () around the array:

在数组周围放置():

Sub test()

       Dim arrCols As Variant

       arrCols = Array(1, 2)

       '/This here works
       Sheet1.Range("$A$1:$B$10").RemoveDuplicates Columns:=Array(1, 2), Header _
            :=xlYes

       '/ Same code fails when the columns array is passed via variable
       '/ Error 5: Invalid procedure call or argument
        Sheet1.Range("$A$1:$B$10").RemoveDuplicates Columns:=(arrCols), Header _
            :=xlYes

 End Sub

It has to do with what vba is expecting to see.

它与vba期待看到的有关。