使用VBA删除重复项
我想使用Visual Basic删除我的Excel工作表中的重复行。 问题是行的数量是可变的。
Sub RemoveDuplicates() Range("A1").Select ActiveSheet.Range(Selection, ActiveCell.CurrentRegion).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes End Sub
这里的问题是Columns:=Array(1, 2)
不是一个variables。 它应该总是从第1
列开始,直到最后一个填充列( .CurrentRegion
)。
有人可以帮帮我吗!
一种方法是dynamic创build数组。
一旦块已经被定义,我们知道该块包含多less个列:
Sub luxation() Dim A1 As Range, rng As Range, cCount As Long Set A1 = Range("A1") Set rng = A1.CurrentRegion cCount = rng.Columns.Count - 1 ReDim ary(0 To cCount) For i = 0 To cCount ary(i) = i + 1 Next i rng.RemoveDuplicates Columns:=(ary), Header:=xlYes End Sub
注意ary()
的封装在最后一行!
也许你想要这样的东西:
Sub RemoveDuplicates() Dim LastCol As Long Dim LastRow As Long Dim ColArray As Variant Dim i As Long ' modify "Sheet1" to your sheet's name With Sheets("Sheet1") ' find last column with data in first row ("header" row) LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column ' find last row with data in column "A" LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ReDim ColArray(0 To LastCol - 1) For i = 0 To UBound(ColArray) ColArray(i) = i + 1 Next i .Range(.Cells(1, 1), .Cells(LastRow, LastCol)).RemoveDuplicates Columns:=(ColArray), Header:=xlYes End With End Sub
加里的学生有正确的答案。
我只是有一点乐趣:
Dim a As Variant With Range("A1").CurrentRegion a = Evaluate("Transpose(Row(1:" & .Columns.Count & "))") ReDim Preserve a(0 To UBound(a) - 1) .RemoveDuplicates Columns:=(a), Header:=xlYes End With