删除具有重复数据VBA的行

时间:2014-05-23 02:43:09

标签: vba excel-vba duplicate-removal excel

我正在努力做一些应该相当简单的事情,但是,我已经阅读了至少15种做法的方法,似乎无法让它发挥作用。

以下是一个示例数据集:

9:30:01 584.7
9:30:01 590
9:30:01 595
9:30:02 584.51
9:30:03 584.62
9:30:04 584.44
9:30:05 584.05

我只想要每秒一行,所以前三行中只需要一行。我不在乎它是第一个还是最后一个,但我一直使用的代码保留了最后一个,在这种情况下为595.

我这样做的方法是使用for循环清除与其下面的行具有相同时间的行的内容。然后我对整个范围进行排序。

我想有一种简单的方法可以简单地从get go中删除额外的行。但是,当我在范围上使用删除时,它不会清除,也不会删除所有重复的行。

以下是我希望数据的样子:

9:30:01 595
9:30:02 584.51
9:30:03 584.62
9:30:04 584.44
9:30:05 584.05

我需要在整张纸上发生这种情况。时间是B列,值是C列。

这是我正在使用的代码,

LastRow = ActiveSheet.UsedRange.row - 1 + _
    ActiveSheet.UsedRange.Rows.Count

For RowNum = 2 To LastRow
    If (Range("B" & RowNum) = Range("B" & RowNum + 1)) Then
    Range("B" & RowNum).EntireRow.Clear
    End If
Next RowNum

Range("A2:C" & LastRow).Sort key1:=Range("B2:B" & LastRow), _
order1:=xlAscending, Header:=xlNo

2 个答案:

答案 0 :(得分:8)

不要循环。使用RemoveDuplicates。比任何循环都快。一行代码。

Sub test()
    ActiveSheet.Range("B:C").RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

编辑:截图

enter image description here

enter image description here

编辑:在Excel 2011 for Mac中不起作用(参见图)。

答案 1 :(得分:2)

这应该可以解决问题:

Sub jzz()
Dim i As Long
For i = 1 To Cells.SpecialCells(xlLastCell).Row 'loop from row 1 to last row
    If Cells(i, 1) <> vbNullString Then 'check if something is in the cell
        If Cells(i, 1) = Cells(i + 1, 1) Then 'check if cell is the same as next cell
            Cells(i + 1, 1).EntireRow.Delete 'if so; delete
            i = i - 1 'go back one row
        End If
    End If
Next i
End Sub

另一种选择是自下而上,如下:

Sub jzz()
Dim i As Long
For i = Cells.SpecialCells(xlLastCell).Row to 1 step -1'loop from last row to row 1
    If Cells(i, 1) <> vbNullString Then 'check if something is in the cell
        If Cells(i, 1) = Cells(i + 1, 1) Then 'check if cell is the same as next cell
            Cells(i + 1, 1).EntireRow.Delete 'if so; delete
        End If
    End If
Next i
End Sub

如果是个人,你更喜欢使用什么。请考虑teylyn的答案,在这种情况下,它非常实用。

相关问题