分割数据并使用vba进行比较

时间:2018-11-06 16:49:26

标签: excel vba excel-vba

当前,我面临一个问题,不知道如何解决。我需要用定界符“ |”分割元素。并且,仅获取Array [0]和Array [3]中的值。然后,我需要将其与其他字符串[varr]进行比较。 arr和varr中的值存储在数组中。

例如,

    Dim arr As Variant

    Dim varr As Variant

arr = 111|Sample1|Test1

arr = 222|Sample2|Test2

arr = 333|Sample3|Test3

varr = 111|Sample1|Test5

varr = 222|Sample2|Test4

varr = 333|Sample3|Test3

在这种情况下,我需要遍历arr / varr并使用定界符“ |”分割字符串并连接array [0]和array [3]。然后,将其与varr(相同的过程)进行比较。我的代码如下:

    Dim x As Variant, y As Variant
Dim match As Boolean
Dim Result(), Result2() As String
Dim DisplayText, DisplayText1, DisplayText2, DisplayText3, DisplayText4, DisplayText5 As String
For Each x In arr
    match = False
    Result = Split(x, "|")
    DisplayText = Result(0)
    DisplayText1 = Result(2)
    DisplayText2 = DisplayText & DisplayText1
    For Each y In varr
        Result2 = Split(y, "|")
        DisplayText3 = Result2(0)
        DisplayText4 = Result2(2)
        DisplayText5 = DisplayText3 & DisplayText4
        If LCase(DisplayText2) = LCase(DisplayText5) Then
            MsgBox "No Change"
            match = True
        End If
    Next y
    If Not match Then
        MsgBox "Change"
    End If
Next

我收到此错误,它指向For Each中的y。 enter image description here

您有什么主意,为什么会遇到此错误?

1 个答案:

答案 0 :(得分:1)

我将不得不添加它作为答案,因为它不会出现在评论中。
这段代码将执行,但是不确定是否会得到您想要的结果-它可能只是问题的工作副本?

Sub Test()

    Dim arr As Variant, varr As Variant
    Dim x As Variant, y As Variant
    Dim Result As Variant, Result2 As Variant
    Dim DisplayText As String, DisplayText1 As String
    Dim Match As Boolean

    arr = Array("111|Sample1|Test1", "222|Sample2|Test2", "333|Sample3|Test3")
    varr = Array("111|Sample1|Test5", "222|Sample2|Test4", "333|Sample3|Test3")

    For Each x In arr
        Result = Split(x, "|")
        DisplayText = Result(0) & Result(2)
        For Each y In varr
            Result2 = Split(y, "|")
            DisplayText1 = Result2(0) & Result2(2)
            If LCase(DisplayText) = LCase(DisplayText1) Then
                MsgBox "No Change"
                Match = True
            End If
        Next y
        If Not Match Then
            MsgBox "Change"
        End If
    Next x

End Sub