不甘心呐,竟然被FOR循环难住了
Public Function strDelSameItemInArr(ByVal strArray As String()) As String()
Dim I As Long, J As Long, K As Long, mCount As Long
mCount = UBound(strArray)
For I = 0 To mCount - 1
For J = I + 1 To mCount
If strArray(I) = strArray(J) Then
For K = J To mCount - 1
strArray(K) = strArray(K + 1)
Next K
ReDim Preserve strArray(mCount - 1)
mCount = mCount - 1
If J = mCount Then
Exit For
End If
End If
Next
Next
Return strArray
End Function
Dim strArray As String() = {"start18", "start36", "start54", "start18", "start18"}
Public?Function?strDelSameItemInArr(ByVal?strArray?As?String())?As?String()
????Return strArray.Distinct().ToArray()
End?Function
'Public Function strDelSameItemInArr(ByVal strArray As String()) As String()
'原代码错误:①格式错误;②调用规范错误(数组只能ByRef)。
Public Function strDelSameItemInArr(strArray() As String) As String()
Dim I As Long, J As Long, K As Long, mCount As Long
'**************************
Dim arrTemp() As String
Dim strTemp$
'**************************
arrTemp = strArray
mCount = UBound(strArray)
For I = 0 To mCount - 1
'For J = I + 1 To mCount
' If strArray(I) = strArray(J) Then
' For K = J To mCount - 1
' strArray(K) = strArray(K + 1)
' Next K
' ReDim Preserve strArray(mCount - 1)
' mCount = mCount - 1
' If J = mCount Then
' Exit For
' End If
' End If
'Next
strTemp = arrTemp(I)
'用于比较的‘基准串’用简单变量,可以提升运行速度
J = I + 1
'下面这段‘筛选’过程,比你原来的方式速度要快得多
Do
If (strTemp = arrTemp(J)) Then
arrTemp(J) = arrTemp(mCount)
mCount = mCount - 1
Else
If (mCount = J) Then Exit Do
J = J + 1
End If
Loop
If (mCount = I + 1) Then Exit For
Next
ReDim Preserve arrTemp(mCount)
'Return strArray '语法错误
strDelSameItemInArr = arrTemp
End Function
Public Sub strDelSameItemInArr(ByRef strArray() As String)
Dim I As Long, J As Long, K As Long, mCount As Long
mCount = UBound(strArray)
For I = mCount To 1 Step -1
For J = I - 1 To 0 Step -1
If strArray(I) = strArray(J) Then
For K = I To mCount - 1
strArray(K) = strArray(K + 1)
Next K
mCount = mCount - 1
ReDim Preserve strArray(mCount)
I = I - 1
End If
Next
Next
End Sub