使用excel vba搜索文件夹/文件

问题描述 投票:0回答:1

目标是创建一个宏,该宏将使用任何输入字符串并搜索指定的目录,并在该目录中的文件中搜索该字符串。绝对的要求是,不仅要检查文件名,还要检查文件的内容。输出应该是结果列表。到目前为止,我得到的是一个看起来像这样的宏:

Sub Test()

    Dim d As String
    Dim searchpath As String
    Dim searchlocation As String

    Cancel = True
    d = Selection.Value

    'change window name to make sure new explorer window is opened for each instance
    'copy string from manual search

    searchpath = "search-ms:displayname=" & d & "%20Results%20&crumb=System.Generic.String%3A"

    searchlocation = "&crumb=location:C%3A%5CUsers%5Csturm%5COneDrive%5CVigiles Capital GmbH%5C01 Vigiles Capital GmbH Team%5C09 Consulting%5C01 SRW%5C01 Peergroup Vergleich%5C05 SR am Westpark%5CDaten%5CZusatz 1"
        If Not d = "" Then
            Call Shell("explorer.exe """ & searchpath & d & searchlocation & "", 1)
        End If

End Sub

这将打开Windows资源管理器,并显示我的搜索结果。我现在需要的是将通过此操作获得的结果放入列表中,然后再次关闭窗口。

绝对世界类将是一个解决方案,它甚至不需要调用Shell,即无需打开资源管理器窗口即可执行相同的操作。

如果可能,我如何使它工作?

excel vba file search
1个回答
0
投票

您尝试搜索哪种文件?其他Excel文件? CSV? ppt?字?下面的代码是我最近完成并一直在使用的某些内容的修改后的版本。假设您正在搜索的文件是.csv,则类似以下代码的文件应该可以工作。尽管您可能必须解析文件名或在搜索字符串中使用“ *”。尚未对此进行测试,但很容易针对其他文件类型进行修改。

Sub SearchDir()

Dim wb as Workbook
Dim ws as Worksheet
Dim filepath as String
Dim filename as String
Dim rng as Range
Dim i as Variant
Dim results as Worksheet
Dim resultslr as long
Dim lastrow as long
Dim searchString as string

Set results = ThisWorkbook.Worksheet("results")

filePath = "C:\Local_Path"
fileName = Dir(filePath & "*.csv")

searchString = "what you're searching for"

Do While fileName <> ""

    If fileName like searchString then
       resultslr = results.Cells(Rows.count, "a").End(xlUp).Row + 1
       results.Cells(resultslr, "a").Resize(1, 1).Value = fileName
     End if

    Set wb = Excel.Workbooks.Open(filePath & fileName)   'opens the file
    Set ws = wb.Worksheets(1)      'sets the worksheet within the csv

    lastrow = ws.Cells(Rows.count, "a").End(xlUp).Row
    Set rng = Range("A2:someEndColumn" & lastrow)   'replace someEndColumn with however your dat ais arranged.

    For each i in rng                                   'searches each cell in the range for your seachString and puts the results in a list on worksheet 'results'
       if i.value Like searchString then
          resultslr = results.Cells(Rows.count, "a").End(xlUp).Row + 1
          results.Cells(resultslr, "a").Resize(1, 1).Value = i.Value
       End if
     Next i    

    wb.Close False               'closes the file

    fileName = Dir                'next file in directory
Loop
`more code for other stuff
end sub
© www.soinside.com 2019 - 2024. All rights reserved.