如何在多个工作簿中搜索单元格信息 - 升级?

如何在多个工作簿中搜索单元格信息 - 升级?

我有几个巨大的 Excel 文件,每个文件都有很多工作表。我必须手动搜索每个文件以查找特定字符串并检查它是否存在于某个地方。

我找到了以下代码这里到目前为止一切正常。

Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String


On Error GoTo ErrHandler
Application.ScreenUpdating = False


'Change as desired
strPath = "c:\MyFolder"
strSearch = "Specific text"

Set wOut = Worksheets.Add
lRow = 1
With wOut
    .Cells(lRow, 1) = "Workbook"
    .Cells(lRow, 2) = "Worksheet"
    .Cells(lRow, 3) = "Cell"
    .Cells(lRow, 4) = "Text in Cell"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder(strPath)

    strFile = Dir(strPath & "\*.xls*")
    Do While strFile <> ""
        Set wbk = Workbooks.Open _
          (Filename:=strPath & "\" & strFile, _
          UpdateLinks:=0, _
          ReadOnly:=True, _
          AddToMRU:=False)

        For Each wks In wbk.Worksheets
            Set rFound = wks.UsedRange.Find(strSearch)
            If Not rFound Is Nothing Then
                strFirstAddress = rFound.Address
            End If
            Do
                If rFound Is Nothing Then
                     lRow = lRow + 1
                    .Cells(lRow, 1) = wbk.Name
                    .Cells(lRow, 2) = wks.Name
                    .Cells(lRow, 3) = rFound.Address
                    .Cells(lRow, 4) = rFound.Value
Else
Exit Do

                End If
                Set rFound = wks.Cells.FindNext(After:=rFound)
            Loop While strFirstAddress <> rFound.Address
        Next

            wbk.Close (False)
            strFile = Dir
        Loop
        .Columns("A:D").EntireColumn.AutoFit
    End With
    MsgBox "Done"

ExitHandler:
    Set wOut = Nothing
    Set wks = Nothing
    Set wbk = Nothing
    Set fld = Nothing
    Set fso = Nothing
    Application.ScreenUpdating = True
    Exit Sub

ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub

但是为了搜索字符串,每次我都必须打开代码并更改路径和搜索词:

strPath = "c:\MyFolder"            
strSearch = "Specific text"

我希望在附图上有一个搜索字段或类似的东西,而不是每次都打开代码并更改路径。可以吗?

在此处输入图片描述

或者例如工作表上包含结果的两个单元格,我可以将路径和搜索词放在哪里,而无需打开代码?

答案1

strPath = ActiveSheet.Range("A1").value 
strSearch = ActiveSheet.Range("B1").value

要制作按钮,请使用开发人员功能区添加表单控件。

相关内容