【问题标题】:Delete rows in Excel based on duplicates in Column根据列中的重复项删除 Excel 中的行
【发布时间】:2016-07-12 20:16:29
【问题描述】:

我想根据列中的重复值删除 Excel 中的行。比方说

Column A      Column B
ABC             1
DEF             2
DEF             3
ABC             1

B 列中,我们有一个重复值。仅使用删除重复功能没有帮助。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    嗯,这段代码完美运行

    ActiveSheet.Range("$A$1:$B$4").RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo
    

    【讨论】:

    • 但这会选择所有列。我有很多列,只想删除基于 1 列的重复项
    • 只需设置而不是 [column_number] 你的列和而不是 [data_range] 你的表格范围ActiveSheet.Range([data_range]).RemoveDuplicates Columns:=[column_number], Header:=xlNo
    • Nope 似乎不起作用。尝试了它的所有变体
    • 请给我看你的变种。如果我能看到你的文件就更好了
    • 我在一列中有一个电子邮件 ID 列表。所以如果有重复,我希望删除重复的行。
    【解决方案2】:

    也许不是最优化的解决方案,但它确实有效

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多