Excel 如何循环遍历以管道分隔的数据值行,并检查是否有任何值与前一行匹配

Excel 如何循环遍历以管道分隔的数据值行,并检查是否有任何值与前一行匹配,excel,vba,for-loop,Excel,Vba,For Loop,我有一个仅为1列且以管道分隔的数据集 7033 | 6010 | 873 6040 | 888 6017 | 6040 | 567 我正在寻找最有效的方法(最好是VBA)来循环遍历列中的所有行,并确定第N行中的任何数据是否等于第N-1行。我希望能够在相邻的列中插入一个值,该值用“Y”或“N”标记何时发生这种情况 在上面的示例中,由于值“6040”,第2行与第1行不匹配,但第3行与第2行匹配 如有任何意见或建议,将不胜感激 任何建议我假设您的数据在表1的A列中。这段代码可以进一步优化,但现在

我有一个仅为1列且以管道分隔的数据集

7033 | 6010 | 873

6040 | 888

6017 | 6040 | 567
我正在寻找最有效的方法(最好是VBA)来循环遍历列中的所有行,并确定第N行中的任何数据是否等于第N-1行。我希望能够在相邻的列中插入一个值,该值用“Y”或“N”标记何时发生这种情况

在上面的示例中,由于值“6040”,第2行与第1行不匹配,但第3行与第2行匹配

如有任何意见或建议,将不胜感激


任何建议

我假设您的数据在表1的A列中。这段代码可以进一步优化,但现在它应该足够快,可以在几秒钟内处理数百行代码

Sub Main()
    Dim i As Long
    Dim j As Long
    Dim str As String
    Dim arr As Variant
    Dim arr2 As Variant 'array of the result
    Dim arrTemp As Variant
    Dim rng As Range

    'put everything into an array
    Set rng = Worksheets("Sheet1").UsedRange.Columns(1)
    arr = rng.Value
    arr2 = arr
    arr2(1, 1) = "" 'delete the first row since there won't be any value above it to compare

    'loop thru the array rows and split the values of each element and compare it with the element above it
    For i = 2 To UBound(arr, 1)
        arrTemp = Split(arr(i, 1), " | ")

        arr2(i, 1) = "No" 'assume there is no match at first
        For j = 0 To UBound(arrTemp)
            If InStr(arr(i - 1, 1), arrTemp(j)) > 0 Then
                arr2(i, 1) = "Yes"
                Exit For 'there was a match get out
            End If
        Next j
    Next i

    'paste the results
    rng.Offset(0, 1).Value = arr2

End Sub
输出


假设数据在一列中,下面的代码将为您提供预期的输出

Private Sub Test()
Dim i As Integer
For i = 4 To 2 Step -1
    j = i - 1
    PrevTempStr = Cells(j, "A")
    CurTempStr = Cells(i, "A")
    PreVal = Split(PrevTempStr, "|") 'Converts into array
    CurVal = Split(CurTempStr, "|")
    If MatchArray(CurVal, PreVal) Then 'Function to check if any of the element of current array matches with previous array
        Cells(i, "B") = "Y" 'Update Value Y in B column if matches
    Else
        Cells(i, "B") = "N"
    End If
Next
End Sub


Private Function MatchArray(Arg1 As Variant, Arg2 As Variant) As Boolean

    For i = LBound(Arg1) To UBound(Arg1)
        For j = LBound(Arg2) To UBound(Arg2)
            If Trim(Arg1(i)) = Trim(Arg2(j)) Then
                MatchArray= True
                Exit Function
            End If
        Next j
    Next i
    MatchArray= False
End Function

到底是哪一部分给你带来了问题?在单元格上循环并使用Split()分隔值,然后使用Match()将每个值与上面单元格中的值进行比较。