Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a folder for keyword

Tags:

excel

vba

I'm looking to search a folder for a keyword term 'fuel', to pull information from returned files into a 'data' sheet.

For instance, I have a folder week numbers (1 - 52 cross the year so in the new year this will contain one folder but will build as the year goes on).
I search this folder for all .doc files contains the word 'fuel'.
You can do this via a Windows search by typing "fuel" in the search function in the top corner and it will display all filenames and all files that contains the word 'fuel'.

I have this for searching for a file that has 'fuel' in its name, but not inside it.

Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
    file = Dir("c:\testfolder\")
    While (file <> "")
        If InStr(file, "fuel") > 0 Then
            MsgBox "found " & file
            Exit Sub
        End If
        file = Dir
    Wend
End Sub
like image 798
JamieB Avatar asked Dec 31 '13 10:12

JamieB


1 Answers

It isn't particularly pretty, but think something like this should work:

Sub loopThroughFiles()
    Dim file As String
    file = FindFiles("C:\TestFolder", "fuel")
    If (file <> "") Then MsgBox file
End Sub

Function FindFiles(ByVal path As String, ByVal target As String) As String
    ' Run The Sheell Command And Get Output
    Dim files As String
    Dim lines
    files = CreateObject("Wscript.Shell").Exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
    lines = Split(files, vbCrLf)

    ' Look for matching files
    Dim curFile As String
    Dim line
    For Each line In lines
        If (Left(line, 11) = "---------- ") Then
            curFile = Mid(line, 12)
        End If

        If (line = target) Then
            FindFiles = curFile
            Exit Function
        End If
    Next

    FindFiles = ""
End Function

Uses the FIND command line and then reads the output (hence needing to use Wscript.Shell) and returns first match, or empty string if no file is found

Following @BLUEPIXY's command FINDSTR /M the function can be replaced by:

Function FindFiles(ByVal path As String, ByVal target As String) As String
    ' Run The Shell Command And Get Output
    Dim files As String
    files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll

    FindFiles = ""
    If (files <> "") Then
        Dim idx As Integer
        idx = InStr(files, vbCrLf)
        FindFiles = Left(files, idx - 1)
    End If
End Function
like image 89
JDunkerley Avatar answered Oct 23 '22 02:10

JDunkerley