2013-04-24 180 views
1

我有一個接近工作但不完全的代碼。我有兩個數組astrArray1和astrArray2,函數findUniques()應該返回兩個數組中的唯一字符串(名稱)。我可以讓代碼返回它們共有的名稱,但它不會爲唯一的名稱返回正確的值。任何幫助,將不勝感激!從兩個字符串數組中返回唯一字符串,連接成一個字符串VBA

下面是代碼:

Function findUniques(astrArray1() As String, astrArray2() As String) As String 


Dim blnMP5 As Boolean 
blnMP5 = True 

Dim counter1 As Long 
Dim counter2 As Long 

Dim uniquesString As String 
uniquesString = " " 

For counter1 = LBound(astrArray1) To UBound(astrArray1) 
    For counter2 = LBound(astrArray2) To UBound(astrArray2) 
    If astrArray1(counter1) <> astrArray2(counter2) Then 
     blnMP5 = False 
    ElseIf astrArray1(counter1) = astrArray2(counter2) Then 
     blnMP5 = True 
    End If 
    If blnMP5 = False Then 
     uniquesString = uniquesString & "," & astrArray2(counter2) 
    End If 
    Next counter2 
Next counter1 

findUniques = uniquesString 
End Function 

回答

0

喜歡這個?

Option Explicit 

Sub Sample() 
    Dim MyAr1(1 To 4) As String 
    Dim MyAr2(1 To 2) As String 

    MyAr1(1) = "aaa": MyAr1(2) = "bbb": MyAr1(3) = "ccc": MyAr1(4) = "ddd" 
    MyAr2(1) = "aaa": MyAr2(2) = "bbb" 

    '~~> This will give you ccc,ddd 
    Debug.Print findUniques(MyAr1, MyAr2) 
End Sub 

Function findUniques(astrArray1() As String, astrArray2() As String) As String 
    Dim i As Long, j As Long 
    Dim uniquesString As String 
    Dim matchFound As Boolean 

    For i = LBound(astrArray1) To UBound(astrArray1) 
     matchFound = False 
     For j = LBound(astrArray2) To UBound(astrArray2) 
      If astrArray1(i) = astrArray2(j) Then 
       matchFound = True 
       Exit For 
      End If 
     Next j 

     If matchFound = False Then uniquesString = uniquesString & "," & astrArray1(i) 
    Next i 

    findUniques = Mid(uniquesString, 2) 
End Function 
+0

謝謝你的幫忙!即使一個數組長於另一個數組,它也可以工作嗎? – user2217895 2013-04-24 20:38:39

+0

查看上面的答案。一個陣列比另一個大:) – 2013-04-24 20:39:56

+0

謝謝!非常感謝您的幫助! – user2217895 2013-04-24 21:19:49

相關問題