2

I am trying to go through an array to find duplicate entries in a single column of that array and delete the entire row.

I am getting figuring out rangeStart, rangeEnd, and lastrow above this and that part is working fine.

data = Range(rangeStart, rangeEnd)

For i = lastrow - 1 To 2 Step -1
    If data(i - 1, x) = data(i, x) Then
        'Delete data(i)
    End If
Next

Any help with this would be awesome!

5
  • are your values in Range(rangeStart, rangeEnd) sorted? Commented Jan 31, 2014 at 15:42
  • Where is x coming from? Commented Jan 31, 2014 at 15:45
  • x is a unique identifier from above. Commented Jan 31, 2014 at 16:10
  • 1
    Easier to create a second empty array of the same size and copy only unique "rows" over. Commented Jan 31, 2014 at 16:14
  • How would I copy the entire row over to another array? Commented Jan 31, 2014 at 18:25

3 Answers 3

3
Sub RemoveDups()
Const COMPARE_COL as Long = 1
Dim a, aNew(), nr As Long, nc As Long
Dim r As Long, c As Long, rNew As Long
Dim v As String, tmp

    a = Selection.Value
    nr = UBound(a, 1)
    nc = UBound(a, 2)

    ReDim aNew(1 To nr, 1 To nc)
    rNew = 0
    v = Chr(0)

    For r = 1 To nr
        tmp = a(r, COMPARE_COL)
        If tmp <> v Then
            rNew = rNew + 1
            For c = 1 To nc
                aNew(rNew, c) = a(r, c)
            Next c
            v = tmp
        End If
    Next r

    Selection.Value = aNew

End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This seems to do what I need it to do!
0

Does this help?:

If data(i - 1, x) = data(i, x) Then
    data(i,x).EntireRow.Delete
End If

4 Comments

Getting a Subscript out of range
lastrow should be equal to (rangeEnd.row - rangeStart.row)
@hstay - OP is not looping through a range (note there is no Set where they assign the range to data, so that line creates a 2-D array from the range values)
Thanks, @TimWilliams, I was blindfolded after seing Range().
0

Why not use Excel's inbuilt Unique options (Data ... Remove Duplicates)?

Another efficient VBA method is to use a Dictionary.

Sub A_Unique_B()

Dim X
Dim objDict As Object
Dim lngRow As Long

Set objDict = CreateObject("Scripting.Dictionary")
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))

For lngRow = 1 To UBound(X, 1)
    objDict(X(lngRow)) = 1
Next

Range("B1:B" & objDict.Count) = Application.Transpose(objDict.Keys)
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.