VBA删除数组中的重复项

时间:2014-06-19 18:53:45

标签: excel excel-vba vba

我的字符串看起来像"苹果//苹果//橙子//"我收到错误"下标超出范围"当我试图删除重复。

我希望我的最终结果看起来像"苹果//橙子//"

Dim duplicateArray() As String
Dim programsArray() As String

duplicateArray() = Split(Sheets("Sheet1").Cells(1, 12).Value, "//")

For j = 0 To UBound(duplicateArray)
    If UBound(Filter(programsArray, duplicateArray(j))) > -1 Then

    Else
    programsArray(UBound(programsArray()) + 1) = duplicateArray(j)

    End If

Next j

    programElement = Join(programsArray, " // ")
    Sheets("Sheet1").Cells(1, 3).Value = programElement

2 个答案:

答案 0 :(得分:1)

动态调整数组大小:

ReDim [Preserve] name(boundlist)

使用“保留”将以前的数据保存在数组

Dim duplicateArray() As String
Dim programsArray() As String

duplicateArray() = Split(Sheets("Sheet1").Cells(1, 12).Value, "//")

For j = 0 To UBound(duplicateArray)
    If UBound(Filter(programsArray, duplicateArray(j))) > -1 Then

    Else
    redim preserve programsArray(UBound(programsArray()) + 2)
    programsArray(UBound(programsArray()) + 1) = duplicateArray(j)

    End If

Next j

    programElement = Join(programsArray, " // ")
    Sheets("Sheet1").Cells(1, 3).Value = programElement

答案 1 :(得分:0)

考虑:

Sub DeDup()
    duplicateArray = Split(Sheets("Sheet1").Cells(1, 12).Value, "//")
    Dim c As Collection
    Set c = New Collection
    On Error Resume Next

    For Each d In duplicateArray
        c.Add d, CStr(d)
    Next d

    programsArray = c(1)
    For i = 2 To c.Count
        programsArray = programsArray & "//" & c(i)
    Next i

    Sheets("Sheet1").Cells(1, 3).Value = programsArray
End Sub