Search code examples
vba

How can I delete a specific element in a string array?


I have created a string array using

Dim stringArray() as String

and used the Split function to enter my data. Is there a way to delete a specific element of this string array? [Something like "stringArray(1).Delete" (This doesn't work)]

I know that I could probably solve this problem by creating a new array or using a collection, but is there a simpler way to solve this problem?

Thanks!


Solution

  • Try this way, please:

    Dim stringArray() as String
    stringArray = split("firstEl,SecondEl,third,fourth", ",")
    
    'To eliminate the third element:
    stringArray(2) = "@#$%&" '2 because of 1D array e based
                             'use a string of characters impossible to exist as another element
    stringArray = Filter(stringArray, stringArray(2), False)
      debug.print Join(stringArray, "|") 'see the returned array in Immediate Window (Ctrl + G being in VBE)
    
    'When you only know the element value:
    dim mtch
    mtch = Application.Match("fourth", stringArray, 0)
    if not IsError(mtch) then
       stringArray(mtch -1) = "@#$%&"
       stringArray = Filter(stringArray, "@#$%&", False)
        debug.print Join(stringArray, "|") 'see the returned array in Immediate Window
    Else
       MsgBox "The searched string could not be found between the array elements..."
    End if