2011-05-03 52 views
0

我有一個包含兩列數據的excel文檔。 第一列有19k行數據,第二列有2k行數據。 第2列中的所有數據都存在於第1列中。 我想刪除第一列中包含第二列數據的所有行。 有沒有辦法如何做到這一點提前> 感謝,Lazialeexcel刪除具有相同數據的行

+0

第二列中是否有大量不同的值?例如,我們是在說4,40,400還是4000個不同的第二列值? – Jubbles 2011-05-03 16:43:51

回答

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 
+0

就像你所做的那樣,通過刪除列B中的值,您正在更改列表以檢查列A中的值。我認爲@Laziale真的希望列A中的單元格被刪除(保留列B),而不是整行。 – Excellll 2011-05-03 18:46:21

+0

@Excelllll - 雖然OP沒有明確說明,如果是這種情況,可以通過刪除EntireRow來輕易修復。讓我們看看OP是否回來了他自己的一些評論。 – 2011-05-03 20:18:07

+0

我想指出你的邏輯在某些情況下不會完成任務。例如,如果列A包含{a,b,c,d,e,f},並且列B包含{f,e,d,c,b,a},則應刪除所有行。但是,您的代碼將保留前3行。 – Excellll 2011-05-03 21:03:29

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 
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 
相關問題