VBA删除包含相同值的数组中的重复值 [英] VBA Removing duplicates values in an array including the same value

查看:829
本文介绍了VBA删除包含相同值的数组中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以使用VBA,也是第一个值删除数组中的所有重复项。只保留不重复的值

There is a way to remove all duplicates in array with VBA, also the first value. Just keeping the not Duplicated values

示例:

Array_1 ['pedro','maria','jose','jesus','pepe','pepe','jose']

结果:

Array_1 ['pedro','maria','jesus']


推荐答案

这个代码:

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

其他解决方案作为 Filter 函数不关心完全匹配 。这个新的需要参考VBA项目中的Microsoft Scripting Runtime。

Additional solution as Filter function doesn't care about 'exact match'. This new one requires reference to Microsoft Scripting Runtime in VBA project.

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

这篇关于VBA删除包含相同值的数组中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆