简体   繁体   中英

Removing element from array visual basic 6

I've an array which consists of multiple strings, I want to remove one of the strings. If my array has one of the same elements so ["a", "b", "b", "c"] and I want to remove one of the b's, my method will remove both. Here's my code so far:

Private Function Search_Array(Character As String) As Boolean

    For Loop_Index = 1 To UBound(Characters_Array)
        If Characters_Array(Loop_Index) = Character Then
            Search_Array = True
            Characters_Array(Loop_Index) = ""
        End If
    Next

End Function

Does anyone have any suggestion as to how I can remove only one of the b's from the array. Thanks a lot.

You just need to exit the loop after setting the first character found to an empty string.

Private Function Search_Array(Character As String) As Boolean

    For Loop_Index = 1 To UBound(Characters_Array)
        If Characters_Array(Loop_Index) = Character Then
            Search_Array = True
            Characters_Array(Loop_Index) = ""
            Exit For
        End If
    Next

End Function

The best way which works for me is that you create new function and in that function you put values in new array, and redim old aray to empty, then you will look which item to add back to old array with if . See the code below.

Private Function arrClean_ARR(arrOld As Variant) As variant
On Error GoTo ErrLn
    Const c_strProcName = "countARR"
Dim i As Long
Dim arrayValues As Variant
Dim count As Long

' put values in new array
arrayValues = arrOld 

count = 0
For i = LBound(arrayValues) To UBound(arrayValues)
  'if value of the new array is "" then don't add in old array. Here you can   put your value (whatever) and it will not be in array. In that way you actualy remove value from array
  If arrayValues(i) <> "" Then
    ReDim Preserve arrOld (count)
    arrOld (i) = arrayValues(i)
    count = count + 1
  End If
Next i
arrClean_ARR = arrOld 
Exit Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM