Home > Net >  How can I delete a specific element in a string array?
How can I delete a specific element in a string array?

Time:08-09

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!

CodePudding user response:

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

CodePudding user response:

Remove String Array Element by Index

Sub RemoveElement(ByRef StringArray() As String, ByVal Index As Long)
    
    Dim nUpper As Long: nUpper = UBound(StringArray) - 1
    
    Dim n As Long

    ' Shift.
    For n = Index To nUpper
        StringArray(n) = StringArray(n   1)
    Next n

    ' Resize.
    ReDim Preserve StringArray(nUpper)

End Sub

Sub RemoveElementTEST()
    
    Const SplitString As String = "A,B,C,D,E"
    
    Dim sArr() As String: sArr = Split(SplitString, ",")
    Debug.Print "Before:  " & Join(sArr, ",")
    
    RemoveElement sArr, 2
    Debug.Print "After 2: " & Join(sArr, ",")
    
    RemoveElement sArr, 4
    Debug.Print "After 4: " & Join(sArr, ",")
    
    RemoveElement sArr, 0
    Debug.Print "After 0: " & Join(sArr, ",")

End Sub

Results

Before:  A,B,C,D,E
After 2: A,B,D,E
After 4: A,B,D
After 0: B,D
  •  Tags:  
  • vba
  • Related