从数组中删除行

时间:2014-01-31 15:37:54

标签: arrays vba excel-vba excel

我正在尝试通过一个数组来查找该数组的单个列中的重复条目并删除整行。

我正在弄清楚rangeStart,rangeEnd和lastrow,并且该部分工作正常。

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

任何帮助都会很棒!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这有帮助吗?:

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

答案 2 :(得分:0)

为什么不使用Excel的内置唯一选项(数据...删除重复项)?

另一种有效的VBA方法是使用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