View Single Post
 
Old 04-24-2018, 06:34 AM
NoSparks NoSparks is offline Windows 7 64bit Office 2010 64bit
Excel Hobbyist
 
Join Date: Nov 2013
Location: British Columbia, Canada
Posts: 842
NoSparks is a glorious beacon of lightNoSparks is a glorious beacon of lightNoSparks is a glorious beacon of lightNoSparks is a glorious beacon of lightNoSparks is a glorious beacon of light
Default

If you have your sht1 showing full screen, then show the VBA environment full screen and hit the Windows Key and Right Arrow Key at the same time, your screen should then be half and half so you can use the F8 key to step one line at a time through your code and watch what happens with the spreadsheet as each line is executed.

I think you'll find that as you deal with each cell of the outer loop (the Do While), the For C2row = 2 to C2TotalRows (inner loop) IF statement will be TRUE at C2row = 2 for all but one value, which will then be TRUE when C2row = 3, so every value from the outer loop will be deleted.


Would be simpler to use range.FIND to see if the values of one list exist in the other. Would also eliminate the inner loop.
When deleting rows it's easiest to work from the bottom up.
Sheets and ranges can be referenced directly in code to eliminate activating sheets back and forth.

See if this works for you
Code:
Sub Removal_of_NonDups()

    Dim sht1 As Worksheet, sht2 As Worksheet
    Dim Lastrow As Long, i As Long, NumRemoved As Long
    Dim rng As Range, fndRng As Range
    
Set sht1 = Worksheets("Customers 1")
Set sht2 = Worksheets("Customers 2")

With sht2
    Set rng = .Range("B2", .Cells(Rows.Count, "B").End(xlUp))
End With

With sht1
    Lastrow = .Cells(Rows.Count, "B").End(xlUp).Row
    For i = Lastrow To 2 Step -1
        Set fndRng = rng.Find(What:=.Cells(i, 2).Value, _
                              LookIn:=xlValues, _
                              LookAt:=xlWhole, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlNext, _
                              MatchCase:=False)
        If fndRng Is Nothing Then   'was not found
            .Rows(i).Delete
            NumRemoved = NumRemoved + 1
        End If
    Next i
End With

MsgBox NumRemoved & "  Non-Duplictes were removed."

End Sub
Reply With Quote