Excel - finding values that “look like”

前端 未结 3 1696
渐次进展
渐次进展 2021-01-16 12:08

I have an excel workbook with a ton of sheets. In the first sheet \"users\" i have userdata, firstname, lastname, email, etc. all neatly split from a CSV file. In the other

3条回答
  •  孤街浪徒
    2021-01-16 12:14

    To check for Mike Anderson, Mike, Anderson or even Anderson, Mike, you can use .Find and .FindNext .

    See this example

    Logic: Use the Excel's inbuilt .Find method to find Mike and once that is found, simply check if the cell also has Anderson

    Sub Sample()
        Dim oRange As Range, aCell As Range, bCell As Range
        Dim ws As Worksheet
        Dim SearchString As String, FoundAt As String
    
        On Error GoTo Err
    
        Set ws = Worksheets("Sheet1")
        Set oRange = ws.Columns(1)
    
        SearchString = "Mike"
    
        Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
                    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                    MatchCase:=False, SearchFormat:=False)
    
        If Not aCell Is Nothing Then
            Set bCell = aCell
    
            If InStr(1, aCell.Value, "Anderson", vbTextCompare) Then _
            FoundAt = aCell.Address
    
            Do
                Set aCell = oRange.FindNext(After:=aCell)
    
                If Not aCell Is Nothing Then
                    If aCell.Address = bCell.Address Then Exit Do
                    If InStr(1, aCell.Value, "Anderson", vbTextCompare) Then _
                    FoundAt = FoundAt & ", " & aCell.Address
                Else
                    Exit Do
                End If
            Loop
        Else
            MsgBox SearchString & " not Found"
            Exit Sub
        End If
    
        MsgBox "The Search String has been found these locations: " & FoundAt
        Exit Sub
    Err:
        MsgBox Err.Description
    End Sub
    

    Screenshot

    enter image description here

    More on .Find and .Findnext here.

提交回复
热议问题