同时在多个工作簿中搜索多个字符串

时间:2013-03-29 23:42:26

标签: vba excel-vba excel-2010 excel

如何自动搜索多个字符串?字符串的数量是可变的,位于A列,Sheet“Plan1”,工作簿“”Book1.xlsm“中。我使用Find Method进行搜索,并使用输入框逐个查找字符串,循环显示多个worbook。我想用这个输入框替换字符串循环。我的部分代码:

    Dim wb As Workbook
Dim SearchString As String
Dim SearchRange As Range, cl As Range
Dim Escolhe_Cor As String
Dim FirstFound As String
Dim ws As Worksheet

str = InputBox("Digite o número a ser procurado")
Escolhe_Cor = InputBox("Escolha uma cor para destacar esse número. De 3 a 56")
Application.FindFormat.Clear

  SearchString = Trim(str)


 For Each wb In Workbooks
   If wb.Name <> "Book1.xlsm" Then
    wb.Activate

 If Len(SearchString) = "8" Then

    For Each ws In ActiveWorkbook.Worksheets
             ' Find first instance on sheet
    Set cl = ws.Cells.Find(What:=SearchString, _
        After:=ws.Cells(1, 1), _
        LookIn:=xlValues, _
        LookAt:=xlWhole, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False, _
        SearchFormat:=False)
             If Not cl Is Nothing Then
               ' if found, remember location
                 FirstFound = cl.Address
                 ' format found cell

            Do 'etc etc

1 个答案:

答案 0 :(得分:2)

尝试以下代码:

 Dim wb As Workbook
    Dim SearchString As String
    Dim SearchRange As Range, cl As Range
    Dim Escolhe_Cor As String
    Dim FirstFound As String
    Dim ws As Worksheet
    Dim searchRng As Range, lastRow As Long, cell As Range


    Dim lastRow As Long
    lastRow = Workbooks("Book1.xlsm").Sheets("Plan1").Range("65000").End(xlUp).Row

    Set searchRng = Workbooks("Book1.xlsm").Sheets("Plan1").Range("A2:A" & lastRow)   '

    For Each cell In searchRng
           SearchString = Trim(cell)

        For Each wb In Workbooks
            If wb.Name <> "Book1.xlsm" Then
                wb.Activate

                If Len(SearchString) = "8" Then

                    For Each ws In ActiveWorkbook.Worksheets
                        ' Find first instance on sheet
                        Set cl = ws.Cells.Find(What:=SearchString, _
                                               After:=ws.Cells(1, 1), _
                                               LookIn:=xlValues, _
                                               LookAt:=xlWhole, _
                                               SearchOrder:=xlByRows, _
                                               SearchDirection:=xlNext, _
                                               MatchCase:=False, _
                                               SearchFormat:=False)
                        If Not cl Is Nothing Then
                            ' if found, remember location
                            FirstFound = cl.Address