0

I have a string that looks like "apples//apples//oranges//" I'm getting an error "subscript out of range" when I try to remove duplicates.

I want my end result to look like "apples//oranges//"

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
7
  • What is the value of index? Commented Jun 19, 2014 at 19:02
  • where do you define programsArray size? Commented Jun 19, 2014 at 19:02
  • sorry, it should be Sheets("Sheet1").Cells(1, 3).Value = programElement Commented Jun 19, 2014 at 19:03
  • programsArray isn't filled in this code sample. Commented Jun 19, 2014 at 19:03
  • I want programsArray to by a dynamic array. How do you define it so that I can add new text to it? Commented Jun 19, 2014 at 19:04

2 Answers 2

1

To dynamicaly resize an array:

ReDim [ Preserve ] name(boundlist)

Use Preserve to keept previous data stored in array

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
Sign up to request clarification or add additional context in comments.

1 Comment

I am still getting the error "subscript out of range" It seems to be from "If UBound(Filter(programsArray, duplicateArray(j))) > -1 Then"
0

Consider:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.