2013-03-29 88 views
0

如何自動搜索多個字符串?字符串的數量是可變的,並且在列A,表格「Plan1」,工作簿「」Book1.xlsm「中。我使用查找方法進行搜索,並使用輸入框逐個查找字符串,以循環查找多個工作簿。我想用這個輸入框代替通過字符串的循環。我的代碼部分:在多個工作簿中同時搜索多個字符串

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 

回答

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 
+0

謝謝@Santosh! –

+1

@CrisReis不客氣:-) – 2013-03-30 02:30:06