首页 > 解决方案 > 在两个不均匀的 Variant 数组之间查找匹配

问题描述

我需要检查 arr1 中的每个字符串是否在 arr2 中有匹配项。

如果匹配,则将“匹配”写入 arr1 旁边的列,如果没有则“不匹配”。

这是我的工作表的外观:

我的工作表的外观

Sub Variant_Array_Question()
'Here is my frankenstein monster of a code
    Dim DocNm As Variant, NroNm As Variant
    Dim i As Long, j As Long
    Dim NroLastRow As Long, DocLastRow As Long

    'Arr1
    DocLastRow = ShStart.Range("Q" & Rows.Count).End(xlUp).Row
    DocNm = ShStart.Range("Q6:Q" & DocLastRow).Value

    'Arr2
    NroLastRow = ShStart.Range("T" & Rows.Count).End(xlUp).Row
    NroNm = ShStart.Range("T6:T" & NroLastRow).Value

    For i = 1 To UBound(DocNm)
        For j = 1 To UBound(NroNm)
            If DocNm(i, 1) = NroNm(j, 1) Then
                'Match was found ==== Run into Problem here
                DocNm(i, 1).Offset(0, 1).Value = "Match"
                Exit For
            End If
        Next j
        If i > UBound(NroNm) Then
            'No match was found ==== Run into Problem here
            DocNm(i, 1).Offset(0, 1).Value = "Not Match"
        End If
    Next i
End Sub

标签: excelvbamatchvariant-array

解决方案


DocNm(i, 1).Offset(0, 1).Value = "Match"对数组没有意义。数组没有Offset属性。

如果您的工作表示例在范围大小方面是真实的,请使用Ranges而不是数组。

为了使用数组并获得您需要的结果,您必须使用第三个数组。将其标注为您的第一个数组 Ubound,但我会更好地转换您的代码:

Sub Variant_Array_Question()
    Dim DocNm As Variant, NroNm As Variant, arrStat As Variant
    Dim i As Long, j As Long, boolFound As Boolean
    Dim NroLastRow As Long, DocLastRow As Long
    Dim ShStart As Worksheet
    Set ShStart = ActiveSheet 'use here your sheet!!!
    'Arr1
    DocLastRow = ShStart.Range("Q" & Rows.Count).End(xlUp).Row
    DocNm = ShStart.Range("Q6:Q" & DocLastRow).value
    ReDim arrStat(1 To UBound(DocNm, 1), 1 To 1) 'arr 3
    'Arr2
    NroLastRow = ShStart.Range("T" & Rows.Count).End(xlUp).Row
    NroNm = ShStart.Range("T6:T" & NroLastRow).value

    For i = 1 To UBound(DocNm)
        For j = 1 To UBound(NroNm)
            If DocNm(i, 1) = NroNm(j, 1) Then
                boolFound = True
                arrStat(i, 1) = "Match"
                Exit For
            End If
        Next j
        If Not boolFound Then
            arrStat(i, 1) = "Not Match"
        End If
        boolFound = False
    Next i
    ShStart.Range("R6").Resize(UBound(arrStat, 1), 1).value = arrStat
End Sub

未经测试,但我认为它会工作。如果你能提供一个可编辑的例子,我会测试它......


推荐阅读