简体   繁体   English

Removeduplicates 无法用于大小取决于数据范围的数组

[英]Removeduplicates fails to work for arrays with size depending on data range

There are 2 set of codes below, the upper one (as comments) doesn't work, while the one below works.下面有 2 组代码,上面的一组(作为注释)不起作用,而下面的一组有效。 My goal is to remove duplicates from a range that I do not know its number of columns beforehand.我的目标是从我事先不知道其列数的范围中删除重复项。 The one above should also create an array similar to Array(1,2,3,4,5).上面的代码还应该创建一个类似于 Array(1,2,3,4,5) 的数组。 Any idea why the one at the bottom works while the one on top doesn't?知道为什么底部的一个有效而顶部的一个无效吗? Thanks in advance!提前致谢! (Pasted the wrong code block earlier.) (之前粘贴了错误的代码块。)

The error I got is Run Time error 5: Invalid procedure call or argument.我得到的错误是运行时错误 5:无效的过程调用或参数。

Sub RemoveDup(datarange As Range)

    Dim ColArray() As Variant
    Dim i As Integer

'    ReDim ColArray(1 To datarange.Columns.Count())
'
'    For i = 1 To datarange.Columns.Count()
'        ColArray(i) = i
'    Next i

    ColArray = Array(1, 2, 3, 4, 5)

    datarange.RemoveDuplicates Columns:=(ColArray), _
        Header:=xlNo

End Sub

You need to start building the array from 0... as follows:您需要从 0... 开始构建数组,如下所示:

Dim datarange As Range
Dim ColArray() As Variant
Dim i As Integer

Set datarange = Range("A1:E6")
ReDim ColArray(0 To datarange.Columns.Count() - 1)

For i = 0 To datarange.Columns.Count() - 1
    ColArray(i) = i + 1
Next i

datarange.RemoveDuplicates Columns:=(ColArray), Header:=xlNo

Note: I've just input the range as Range("A1:A6") but you can specify whatever you want.注意:我刚刚将范围输入为 Range("A1:A6") 但您可以指定任何您想要的。

That's my version as a parametrized sub and use of With这是我作为参数化子版本和With使用的版本

Sub RemoveDup(datarange As Range)
' removes duplicate taking all columns into account
Dim i As Long
Dim varItems() As Variant
    With datarange
        ReDim varItems(0 To .Columns.Count - 1)
        For i = 1 To .Columns.Count
            varItems(i - 1) = i
        Next i
        .RemoveDuplicates Columns:=(varItems), Header:=xlNo
    End With
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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