有一种方法可以使用 VBA 删除数组中的所有重复项,包括第一个值。仅保留不重复的值
例子:
Array_1 ['pedro','maria','jose','jesus','pepe','pepe','jose']
Run Code Online (Sandbox Code Playgroud)
结果:
Array_1 ['pedro','maria','jesus']
Run Code Online (Sandbox Code Playgroud)
试试这个代码:
Sub Remove_All_Duplicated()
Dim Array_1
Array_1 = Array("pedro", "maria", "jose", "jesus", "pepe", "pepe", "jose")
Dim Array_2()
Dim eleArr_1, x
x = 0
For Each eleArr_1 In Array_1
If UBound(Filter(Array_1, eleArr_1)) = 0 Then
ReDim Preserve Array_2(x)
Array_2(x) = eleArr_1
x = x + 1
End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
作为函数的附加解决方案Filter不关心“完全匹配”。这一新功能需要在 VBA 项目中引用 Microsoft Scripting Runtime。
Sub alternative()
Dim Array_1
Array_1 = Array("pedro", "pedro maria", "maria", "jose", "jesus", "pepe", "pepe", "jose")
Dim Array_2()
Dim Array_toRemove()
Dim dic As New Scripting.Dictionary
Dim arrItem, x As Long
For Each arrItem In Array_1
If Not dic.Exists(arrItem) Then
dic.Add arrItem, arrItem
Else
ReDim Preserve Array_toRemove(x)
Array_toRemove(x) = dic.Item(arrItem)
x = x + 1
End If
Next
For Each arrItem In Array_toRemove
dic.Remove (arrItem)
Next arrItem
Array_2 = dic.Keys
'quic tests to remove when unnecessary
Debug.Print UBound(Array_2), UBound(Array_toRemove)
Debug.Print Join(Array_2, "/")
End Sub
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40455 次 |
| 最近记录: |