获取与搜索“字符串”匹配的特定单元格的行号,在没有循环的特定列中-列具有多个匹配项

时间:2019-06-07 05:33:22

标签: excel vba

获取与搜索“字符串”匹配的特定单元格的行号(在没有循环的特定列中-列具有多个匹配项”

我想获取特定列中匹配字符串的行号而不进行循环,因为我有超过50000条记录,而且我不想循环每一行来查找

Sub Mismatch()
    Dim sht As Worksheet

    Set Sht5 = ThisWorkbook.Worksheets("Result")

    Dim FindString As String
    FindString = "FAIL"    

    Sht5.Activate
    Columncount = Sht5.Range(Cells(1, 1), Cells(1, 1000)).Cells.SpecialCells(xlCellTypeConstants).Count 'CODE NEED TO BE UPDATED WITH COLUMN LENGTH
    'To find the column count

    lastReportRow = Sht5.Range("B" & Rows.Count).End(xlUp).row
    'to find the last used row

    For i = 2 To Columncount + 1
        Set Valuefound = Sht5.Range(Cells(2, i), Cells(lastReportRow, i)).Find(FindString, After:=Range("B2"), LookIn:=xlValues)

        If Valuefound Is Nothing Then
            MsgBox "Value not found"   
        Else
            For r = 2 To lastReportRow
                ActualString = Sht5.Cells(r, i).Value
                If FindString = ActualString Then
                    MsgBox r
                Else

                End If
                'For x = 2 To lastReportRow
            Next    
        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:1)

您可以使用Match:

    '...
    lastReportRow = Sht5.Range("B" & Rows.Count).End(xlUp).row


    For i = 2 To Columncount + 1

        Set rng = Sht5.Range(Sht5.Cells(2, i), Sht5.Cells(lastReportRow, i))
        Do
            m = Application.Match(FindString, rng, 0)
            If IsError(m) Then Exit Do '<< not found: exit search for this column
            Debug.Print "Found '" & FindString & "' at " & rng.Cells(m).Address
            'reset search range
            Set rng = Sht5.Range(rng.Cells(m+1), Sht5.Cells(lastReportRow, i))
        Loop

     Next i
End Sub

答案 1 :(得分:0)

请参见您的代码,您可以替换:

此:

For i = 2 To Columncount + 1


Set Valuefound = Sht5.Range(Cells(2, i), Cells(lastReportRow, 
 i)).Find(FindString, After:=Range("B2"), LookIn:=xlValues)

    If Valuefound Is Nothing Then
        MsgBox "Value not found"

    Else
      For r = 2 To lastReportRow
         ActualString = Sht5.Cells(r, i).Value
         If FindString = ActualString Then
           MsgBox r
         Else

         End If
        'For x = 2 To lastReportRow
        Next

    End If


     Next

与此:

Set Valuefound = sht5.UsedRange.Find(FindString, After:=Range("B2"), LookIn:=xlValues, lookat:=xlWhole)

    If Valuefound Is Nothing Then
        MsgBox "Value not found"

    Else

        MsgBox Valuefound.Row

    End If

Valuefound.row将为您提供确切的行。您也可以添加Valuefound.column以获得Valuefound的列号

此外,您可以根据此link添加Range.FindNext,以访问数据中多次出现的值。