行号的两列匹配

时间:2015-06-25 08:33:02

标签: excel-vba match string-matching vba excel

我一直在使用强力代码行进行两列匹配,看起来像这样:

For K = 1 To TPrice.ListRows.Count
    If TPrice.DataBodyRange(K, 2).Value = str3 And TPrice.DataBodyRange(K, 3).Value = project_name Then
        r = K + 2
        Exit For
    End If
Next K

如果变量str3在第2列上是非唯一的,并且变量project_name在第3列上也是非唯一的。但是当它们在同一行时是“匹配的”。数据集可能类似于:

two column match

我希望匹配john smith,例如,返回值是表格行3或行号4.但显然,数据集将会更大,我将不得不关于同一行中其他列的数据,例如,约翰·史密斯的就业历史等。

我最近接触过一些数组知识(谢谢拉尔夫!)并考虑这样一个:

Public Sub Finding_John_Smith()
Dim vArr As Variant
Dim lCount As Long
Dim V As Long

vArr = ThisWorkbook.Worksheets("names").ListObjects(1).DataBodyRange.Value2

    For lCount = LBound(vArr) To UBound(vArr)
        Select Case vArr(lCount, 1)
        Case "john"
            If vArr(lCount, 2) = "Smith" Then
                MsgBox "you found a match!"
                V = lCount
            End If
        Case Else
            MsgBox "name cannot be found!"
        End Select
    Next lCount

    End Sub

我只是想知道你们的专家哪一个可能更快,或者你可能有任何个人建议!非常感谢你的时间。

1 个答案:

答案 0 :(得分:1)

您可以调整以下内容以获得有效的内容......

Dim FullName As String: FullName = "John Smith"

Dim tbl As ListObject: Set tbl = ActiveSheet.ListObjects("Table1")
Dim SearchArr() As String: SearchArr = Split(FullName, " ")

Application.Goto tbl
With tbl
    .Range.AutoFilter Field:=1, Criteria1:=SearchArr(0)
    .Range.AutoFilter Field:=2, Criteria1:=SearchArr(1)
    Dim Rng As Range: Set Rng = tbl.DataBodyRange.SpecialCells(xlCellTypeVisible)
    .Range.AutoFilter Field:=1
    .Range.AutoFilter Field:=2
End With