2013-04-08 176 views

回答

3

试试这个代码:

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。

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 
+0

感谢我也是我看到了实际使用的**使用ReDim保留** – 2013-04-08 11:34:53

+1

我很高兴你喜欢这个解决方案。但是,我已经意识到首先想法的一些缺点,因此我添加了其他解决方案。 – 2013-04-08 13:12:57

0

如何创建一个新的A_temp1()不重复,使用过滤器()VBA函数:

Dim A_temp1() As String 
    Dim NUMERO1 As Long 
    Dim NUMERO2 As Long 
    Dim DATO1 As Variant 

NUMERO1 = 0 
For Each DATO1 In Array_1 
    If UBound(Filter(Array_1, DATO1)) > 0 Then 
     Array_1(NUMERO1) = vbNullString 
    End If 
    NUMERO1 = NUMERO1 + 1 
Next DATO1 

NUMERO2 = 0 
For NUMERO1 = LBound(Array_1) To UBound(Array_1) 
    If Array_1(NUMERO1) <> vbNullString Then 
    ReDim Preserve A_temp1(NUMERO2) 
    A_temp1(NUMERO2) = Array_1(NUMERO1) 
    NUMERO2 = NUMERO2 + 1 
    End If 
Next NUMERO1 
0

这里是另一个版本:

Public Sub ShortVersion() 
    Dim varInput: varInput = Array("pedro", "pedro maria", "maria", "jose", "jesus", "pepe", "pepe", "jose") 
    Dim colOutput As Collection: Set colOutput = New Collection 
    Dim i As Long: For i = LBound(varInput) To UBound(varInput) 
     If UBound(Split(Chr(1) & Join(varInput, Chr(1) & Chr(1)) & Chr(1), Chr(1) & varInput(i) & Chr(1))) = 1 Then 
      colOutput.Add varInput(i) 
     End If 
    Next i 
End Sub 

优点:

  • 较短码
  • 的决定标准是独立循环的后面的迭代的,所以如果你在你的算法构建它,你可以用第一个元素进行而无需等待有关后来者
  • 决定不依赖于MS脚本运行

缺点:

  • 效率较低对于更大的阵列
  • 输出集合而不是数组(需要一个循环转换成数组,如果是需要的话)
  • 假设数组只包含文本和ASCII 1(SOH)不 出现的任何地方(这是很可能的,然而)