如何完全删除重复的条目

时间:2013-12-05 20:47:32

标签: excel vba excel-vba duplicate-removal

我在Excel中有一个列,使用vba我试图检查该列中是否有重复的条目然后删除重复和主条目,因此将不再有与该条目相关的值。这样做的方法是什么?

 Input column=>

  1
  2
  3
  1
  4
  5
  2

desired output column =>

 3
 4
 5

其实我的参赛作品是文字但是,我举了数字例子说清楚

答案后我的代码变成了

Last_Row = ws1.Cells(Rows.Count, "G").End(xlUp).Row

Columns("G:H").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("G2", "G" & Last_Row) _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Range("G1", "H" & Last_Row)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Dim i As Integer

i = 2
While (i < Last_Row + 1 And Not IsEmpty(Cells(i, 7).Value))
If Cells(i, 7) = Cells(i + 1, 7) Then
    Range("G" & i + 1, "H" & i + 1).Delete Shift:=xlUp
    Range("G" & i, "H" & i).Delete Shift:=xlUp
End If

If Not Cells(i, 7) = Cells(i + 1, 7) Then
i = i + 1
End If

Wend

4 个答案:

答案 0 :(得分:2)

这很有效。我没有试过优化它或任何东西。

Dim v As Variant
Dim vOut As Variant
Dim ditch() As Integer
Dim i As Long, j As Long, n As Long
'Read input column into 2D array
v = Range("A1:A7").Value
'Mark which inputs to ditch (mark as 1 if duplicate, keep at 0 if not)
ReDim ditch(LBound(v, 1) To UBound(v, 1))
For i = LBound(v, 1) To UBound(v, 1)
    For j = i + 1 To UBound(v)
        If ditch(j) = 0 And v(j, 1) = v(i, 1) Then
            ditch(i) = 1
            ditch(j) = 1
        End If
    Next j
Next i
'How many non-duplicates are there?
n = UBound(v, 1) - LBound(v, 1) + 1 - WorksheetFunction.Sum(ditch)
'Put non-duplicates in new 2D array
ReDim vOut(1 To n, 1 To 1)
j = 0
For i = LBound(v, 1) To UBound(v, 1)
    If ditch(i) = 0 Then
        j = j + 1
        vOut(j, 1) = v(i, 1)
    End If
Next i
'Write array to sheet
Range("B1").Resize(n).Value = vOut

答案 1 :(得分:1)

不使用VBA,如果您的数据在Row1中开始,则复制了=COUNTIF(A:A,A1)的“帮助”列以识别重复项。过滤辅助列并删除显示大于1的值的行可能适合您。

答案 2 :(得分:0)

在Excel 2007中

  

单击功能区中的“数据”选项卡   突出显示您的选择   单击“删除重复项”

答案 3 :(得分:0)

创建宏Excel。您的数据应位于第一列,工作表称为“Sheet1”

Columns("A:A").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A2"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
    .SetRange Columns("A")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Dim i As Integer
Dim b As Boolean

i = 1
b = False
While Cells(i, 1) > 0
    While Cells(i, 1) = Cells(i + 1, 1)
        Rows(i + 1).Delete
        b = True
    Wend
    If b = True Then
        Rows(i).Delete
        b = False
        i = i - 1
    End If
    i = i + 1
Wend