比较两个动态字符串数组

时间:2014-10-20 23:59:54

标签: arrays excel vba excel-vba

我正在寻找一些指导和经验。我有一个VBA模块,可以创建两个字符串。见下文。我想用一个数组来比较两个叮当并写下成功的比赛或者#34;没有比赛"元素到第三个数组或直接到工作表。 第二部分是""" Arr2与Arr1的匹配。所以下面的例子是88%。

> Arr1 result  
> 726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X
> Arr2 result
> 726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X

任何建议都会很棒。

2 个答案:

答案 0 :(得分:1)

以下是使用简单for循环完成任务的一种方法。

Sub compareStrings()
    Dim str1 As String
    Dim str2 As String
    str1 = "726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"
    str2 = "726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"

    Dim Arr1 As Variant
    Dim Arr2 As Variant
    Dim ArrResults As Variant

    Arr1 = Split(str1, ",")
    Arr2 = Split(str2, ",")

    Dim countMatches As Integer
    countMatches = 0

    ReDim ArrResults(UBound(Arr1))

    For i = LBound(Arr1) To UBound(Arr1)
        If Arr1(i) = Arr2(i) Then
            ArrResults(i) = "Matches"
            countMatches = countMatches + 1
        Else
            ArrResults(i) = "No Match"
        End If
    Next i

    'Print out the results array in debug window
    For Each entry In ArrResults
        Debug.Print entry
    Next entry

    Dim ratio As Double
    ratio = countMatches / (UBound(Arr1) + 1)

    MsgBox (ratio * 100 & "%")
End Sub

消息框将显示:

enter image description here


立即窗口将显示结果数组值,如下所示:

enter image description here

答案 1 :(得分:0)

试试这个:

Sub Test()
    Dim str1 As String, str2 As String
    Dim arr, i As Long, cnt As Long

    str1 = "726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"
    str2 = "726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X"

    For i = LBound(Split(str1, ",")) To UBound(Split(str1, ","))
        If Not IsArray(arr) Then
            arr = Array(IIf(Split(str1, ",")(i) = _
                Split(str2, ",")(i), "Match", "NoMatch"))
        Else
            ReDim Preserve arr(UBound(arr) + 1)
            arr(UBound(arr)) = IIf(Split(str1, ",")(i) = _
                Split(str2, ",")(i), "Match", "NoMatch")
        End If
    Next

    '~~> Check the array
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
        If arr(i) = "Match" Then cnt = cnt + 1
    Next
    '~~> output the percentage
    MsgBox Format(cnt / (UBound(arr) + 1), "0.00%")
End Sub