从两个字符串数组中返回唯一字符串,在一个字符串VBA中连接

时间:2013-04-24 19:50:24

标签: arrays vba for-loop boolean string-concatenation

我有一个接近工作但不完全的代码。我有两个数组astrArray1和astrArray2,函数findUniques()应该返回两个数组中的唯一字符串(名称)。我可以获取代码以返回它们共有的名称,但它不会返回唯一的值的正确值。任何帮助,将不胜感激!

以下是代码:

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

1 个答案:

答案 0 :(得分: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