[英]Delete rows in Excel based on duplicates in Column
I want to delete the rows in Excel based on duplicate values in a column. 我想基于列中的重复值删除Excel中的行。 Let's say
比方说
Column A Column B
ABC 1
DEF 2
DEF 3
ABC 1
In column B
, we have a duplicate value. 在
B
列中,我们有一个重复的值。 Going with just the remove duplicate function doesn't help. 仅使用删除重复功能没有帮助。
好吧,这段代码可以完美地工作
ActiveSheet.Range("$A$1:$B$4").RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo
Maybe not the most optimized solution, but it does the work 也许不是最优化的解决方案,但它可以完成工作
Public Sub DeleteDuplicates()
Dim rng As Range, cell As Range, find As Range, previous As Range
Set rng = Worksheets("Test").Range("A:A")
' For each cell of the column
For Each cell In rng
' Check duplicates only if the cell is not empty
If Trim(cell) <> "" Then
' Search for the same value in column A
Set find = rng.find(What:=cell, After:=cell, LookAt:=xlWhole, MatchCase:=True)
' if a result is found
If Not find Is Nothing Then
Do
Set previous = Nothing
' If the column B is the same, save the row as "to be deleted"
' The delete is not now otherwise the FindNext won't work
If find.Offset(, 1) = cell.Offset(, 1) Then
Set previous = find
End If
Set find = rng.FindNext(find)
' If a duplicate was found, delete the raw
If Not previous Is Nothing Then
previous.EntireRow.Delete
End If
' if no more duplicate, exit the do loop
If find Is Nothing Then
Exit Do
End If
' if address of the result is the same as the clel, exit the do loop
If cell.Address = find.Address Then
Exit Do
End If
Loop While True
End If
End If
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.