在几个打开的工作簿中查找字符串

时间:2013-03-12 01:35:01

标签: vba excel-vba excel-2010 excel

如何在多个打开的工作簿中查找字符串并为该行着色。字符串可以在每个工作表中重复,并且可以出现在A,B或C列中。此代码是否可以适用于更多工作簿? 我找到了一个工作簿的代码:

        Sub Search_String()

    Dim SearchString As String
    Dim SearchRange As Range, cl As Range
    Dim Escolhe_Cor As Long
    Dim FirstFound As String
    Dim sh As Worksheet

    ' Set Search value
    SearchString = 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
    ' loop through all sheets
    For Each sh In ActiveWorkbook.Worksheets
        ' Find first instance on sheet
        Set cl = sh.Cells.Find(What:=SearchString, _
            After:=sh.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlPart, _
            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
                cl.EntireRow.Font.Bold = True
                cl.EntireRow.Interior.ColorIndex = Escolhe_Cor
                ' find next instance
                Set cl = sh.Cells.FindNext(After:=cl)
                ' repeat until back where we started
            Loop Until FirstFound = cl.Address
        End If
    Next
End Sub

1 个答案:

答案 0 :(得分:1)

您提供的信息是什么,看起来您只需要将当前代码添加到循环中。这将查看每个打开的工作簿,因此如果您不想将其应用于所有这些工作簿,则可以使用正则表达式来标识工作簿名称。

For Each wb In Workbooks
   'If you only want certain open workbooks searched use this If statement:
   If wb.name = *criteria* Then
      wb.Activate
     'run your code that loops through each sheet
   End If
Next wb