2016-12-17 104 views
1

我想使用Visual Basic删除我的Excel工作表中的重复行。问题是行的数量是可变的。使用VBA删除重复项

Sub RemoveDuplicates() 
    Range("A1").Select 
    ActiveSheet.Range(Selection, ActiveCell.CurrentRegion).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes 
End Sub 

这里的问题是,Columns:=Array(1, 2)不是一个变量。它应该始终从列1直到最后一个填充列(.CurrentRegion)。

有人可以帮助我!

回答

1

一种方法是动态创建数组。

一旦块已经被定义,我们知道该块到底有多少列包含:

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()在最后一行封装!

+0

有趣括号如何导致数组传递BYVAL。我已经放弃了我的回答,直到我看到你和Shai Rado使用它们。荣誉 – 2016-12-17 20:18:16

1

也许你想是这样的:

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 
1

加里的学生有正确的答案。

我只是有一点点的乐趣:

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