excel删除具有相同数据的行

时间:2011-05-03 16:06:17

标签: excel

我有一个包含两列数据的excel文档。 第一列包含19k行数据,第二列包含2k行数据。 第2列中的所有数据都存在于第1列中。 我想删除第一列中包含第二列数据的所有行。 有办法怎么做?> 在此先感谢Laziale

3 个答案:

答案 0 :(得分:0)

使用grep执行此操作可能要容易得多:

将每列导出到文件并执行“grep -v”。这是一个例子:

$ cat col1.txt 
A
B
C
D
$ cat col2.txt 
B
D
$ grep -v -f col2.txt col1.txt 
A
C

答案 1 :(得分:0)

使用VBA可能是最简单的方法。尝试以下宏。它将删除A列中与B列中任何值匹配的所有单元格。如果您需要对其他列执行此操作,只需调整代码以匹配工作簿的设计。

Sub removematches()

Dim firstcolumn() As Variant
Dim colA As Range
Dim colB As Range
Dim i As Long, del As Long

'This will set the ranges to look in.  Note that this will only work for data with no blank cells.  If you have blank cells, you can change these Set statements to the following:
' Set colA = Range("A1:A100") if you have 100 rows you want to look at.
Set colA = Range("A1", Range("A1").End(xlDown))
Set colB = Range("B1", Range("B1").End(xlDown))

firstcolumn = colA

ReDim Preserve firstcolumn(1 To UBound(firstcolumn), 1 To 2) As Variant
i = 1
del = 0

Do While i <= UBound(firstcolumn)
    firstcolumn(i, 2) = Application.WorksheetFunction.CountIf(colB, firstcolumn(i, 1))
    If firstcolumn(i, 2) > 0 Then
        Range("A1").Offset(i - del - 1, 0).Delete Shift:=xlUp
        del = del + 1
    End If
    i = i + 1
Loop

End Sub

答案 2 :(得分:0)

此代码将通过A列工作,并删除任何具有出现在B列任何行中的值的行。它假设A列和B列都在第1行开始:

Sub RemoveDuplicates()

    Dim colB As Variant, iRow As Long
    colB = Range("B1:B2000") //Add you reference for column B

    For iRow = Range("A1").End(xlDown).Row To 1 Step -1
        If Not IsError(Application.Match(Cells(iRow, 1), colB, 0)) Then
            Cells(iRow, 1).EntireRow.Delete
        End If
    Next iRow  

End Sub