excelvbaduplicates

Delete duplicate rows without deleting End Row in vba


As I add an End row to a range I want to delete any rows above that have the same value in columnA. This code saves the new row I am adding but also keeps the first row of any duplicates and leaves the rows blank instead of deleted.

Private Sub clear()

Dim x As Long
x = Cells(Rows.Count, 1).End(xlUp).Offset(-1).Row
Range("A1:Z" & x).RemoveDuplicates Columns:=1, Header:=xlNo

End Sub
 

Solution

  • Delete Duplicates

    Initial and Final Screenshot

    A Calling Procedure (Usage)

    Sub DeleteDupes()
    
        DeleteDuplicates ActiveSheet
        ' Or:
        'DeleteDuplicates ActiveSheet, 1 ' 1 is default
    
    End Sub
    

    The Helper Method

    Sub DeleteDuplicates( _
           ByVal ws As Worksheet, _
           Optional ByVal DuplicatesColumn As Long = 1, _
           Optional ByVal TopRowsToKeep As Long = 1, _
           Optional ByVal BottomRowsToKeep As Long = 1)
    
        Const PROC_TITLE As String = "Delete Duplicates"
        
        Dim irg As Range, IniRowsCount As Long, DelRowsCount As Long
        
        With ws.Range("A1")
            ' Remove duplicates.
            With .CurrentRegion
                IniRowsCount = .Rows.Count - BottomRowsToKeep
                If IniRowsCount <= TopRowsToKeep Then
                    MsgBox "Too few rows in ""'" & ws.Name & "'!" _
                        & .Address(0, 0) & """!", vbExclamation, PROC_TITLE
                    Exit Sub ' too few rows
                End If
                Set irg = .Resize(IniRowsCount - TopRowsToKeep) _
                    .Offset(TopRowsToKeep)
                irg.RemoveDuplicates Columns:=DuplicatesColumn, Header:=xlNo
            End With
            ' Delete empty rows.
            With .CurrentRegion
                DelRowsCount = IniRowsCount - .Rows.Count
                If DelRowsCount < 1 Then
                    MsgBox "No duplicates found in ""'" & ws.Name & "'!" _
                        & irg.Address(0, 0) & """!", vbExclamation, PROC_TITLE
                    Exit Sub ' no duplicates found
                End If
                .Offset(.Rows.Count).Resize(DelRowsCount).Delete Shift:=xlShiftUp
            End With
        End With
    
        MsgBox DelRowsCount & " row" & IIf(DelRowsCount = 1, "", "s") _
            & " of duplicates deleted.", vbInformation, PROC_TITLE
    
    End Sub