我有一个由多个字符串组成的数组,我想删除其中一个字符串。如果我的数组有一个相同的元素["a", "b", "b", "c"]
并且我想删除其中一个b,我的方法将删除它们。到目前为止,这是我的代码:
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
有没有人有任何关于我如何才能从数组中删除其中一个b的建议。非常感谢。
答案 0 :(得分:2)
在将找到的第一个字符设置为空字符串后,您只需要退出循环。
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
答案 1 :(得分:0)
对我有用的最好的方法是你创建新的函数,在这个函数中你将值放在新的数组中,并将旧的aray重新设置为空,然后你将查看哪个项添加回旧的数组if。请参阅下面的代码。
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