为什么我的代码无法将第一个字符串拆分为子字符串

时间:2018-10-09 12:55:43

标签: excel vba excel-vba

我写了一段比较两个字符串的代码。字符串如下:

  • 第一个字符串/数组:“ ABC; CDE; GBH”
  • 第二个字符串/数组:“ ABC; CDE; GBH; LLL”

比较完成后,我希望“ LLL”位于第三个单元格中。除了在第一个字符串甚至没有单个分号的情况下,它都不会给我结果。换句话说,第一个字符串是“ ABC”(不带分号),然后在第三列中返回“ CDE; GBH; LLL”。

代码:

Function CompareTwo(txt As String, txt2 As String) As String
    Dim a, b
    With CreateObject("Scripting.Dictionary")
        .CompareMode = vbTextCompare
        For Each a In Split(txt, ";")
            For Each b In Split(txt2, ";")
                If InStr(Trim(a),Trim(b)) <= 0 then .add Trim(b), nothing
            Next b
         Next a
         If .Count > 0 Then CompareTwo = Join(.keys, ";")
    End With
End Function

1 个答案:

答案 0 :(得分:1)

如果要查找第二个字符串中不在第一个字符串中的部分,请尝试此操作。您可以使用Match而不是循环。我认为您的代码会(可能)出错,因为您尝试多次添加同一密钥。

Function CompareTwo(txt As String, txt2 As String) As String

Dim b

With CreateObject("Scripting.Dictionary")
    .CompareMode = vbTextCompare
    For Each b In Split(txt2, ";")
        If IsError(Application.Match(Trim(b), Split(txt, ";"), 0)) Then .Add Trim(b), Nothing
    Next b
    If .Count > 0 Then CompareTwo = Join(.keys, ";")
End With

End Function

enter image description here