delete non duplicate data in excel using VBA

孤街浪徒 提交于 2019-12-02 09:38:53

Like I mentioned in my comment above, the main flaw in the code logic is that it will fail if the data is not sorted. You need to approach the problem with a different logic

Logic:

  1. Use Countif to check of the value occurs more than once.
  2. Store the row number in a temp range in case more than one match is found
  3. Delete the temp range at the end of the code. We could have deleted each row in a loop but then that will slow down your code.

Code:

Option Explicit

Sub mukjizat2()
    Dim ws As Worksheet
    Dim i As Long, lRow As Long
    Dim delRange As Range

    '~~> This is your sheet
    Set ws = ThisWorkbook.Sheets("process")

    With ws
        '~~> Get the last row which has data in Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Loop through the rows
        For i = 2 To lRow
            '~~> For for multiple occurances
            If .Cells(i, 2).Value <> "" And .Cells(i, 3).Value <> "" Then
                If Application.WorksheetFunction.CountIf(.Columns(2), .Cells(i, 2)) = 1 And _
                Application.WorksheetFunction.CountIf(.Columns(3), .Cells(i, 3)) = 1 Then
                    '~~> Store thee row in a temp range
                    If delRange Is Nothing Then
                        Set delRange = .Rows(i)
                    Else
                        Set delRange = Union(delRange, .Rows(i))
                    End If
                End If
            End If
        Next
    End With

    '~~> Delete the range
    If Not delRange Is Nothing Then delRange.Delete
End Sub

ScreenShot:

Alfa Bachtiar

I know the problem now, hehe.

The code that sid gave me also detect the duplication inter-column

So, my solution is, I just cut the duplicates and paste it to other sheet

Sub hallelujah()

    Dim duplicate(), i As Long
    Dim delrange As Range, cell As Long
    Dim delrange2 As Range

    x = 2

    Set delrange = Range("b1:b30000") 
   Set delrange2 = Range("c1:c30000")

    For cell = 1 To delrange.Cells.Count
        If Application.CountIf(delrange, delrange(cell)) > 1 Then
            ReDim Preserve duplicate(i)
            duplicate(i) = delrange(cell).Address
            i = i + 1
        End If
    Next
    For cell = 1 To delrange2.Cells.Count
    If Application.CountIf(delrange2, delrange2(cell)) > 1 Then
    ReDim Preserve duplicate(i)
    duplicate(i) = delrange(cell).Address
    i = i + 1
    End If
   Next

    For i = UBound(duplicate) To LBound(duplicate) Step -1
        Range(duplicate(i)).EntireRow.Cut
        Sheets("output").Select
        Cells(x, 1).Select
        ActiveSheet.Paste
        Sheets("process").Select
        x = x + 1
    Next i
end sub

I took someone's answer in another question and modify it a bit, just need to modify little bit more to detect duplication base on similarity

Thanks all!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!