-7

Can anyone please help me with a vba code that would search for a user input keyword inside a text file in all the folders and sub folders of a shared drive. And, if the keyword is found in the text file, it should return the folder name and path that contains the text file.

I have a windows form, wherein users can input a keyword and when the user hit the search button, it has to perform the above function.

For example: If a user search for a keyword like "Business", it should look in the for "Business" in all of the text files in all of the folders and sub folders in the shared drive. And if it is found, it should return the folder name and its path containing the file. Example of output

Folder name: ABC Folder path: C:\office\ABC

Can anyone please help me with the code Thanking you in advance.

Here is my code

enter code here

Public Sub FindFiles()

'Added reference to 'Microsoft Shell Controls And Automation'

Dim shl As Shell32.Shell

Dim fol As Shell32.Folder

Dim row As Long

Set shl = New Shell32.Shell

Set fol = shl.Namespace("C:\Users\")

row = 1

ProcessFolderRecursively fol, row

End Sub

Private Sub ProcessFolderRecursively(fol As Shell32.Folder, ByRef row As Long)

Dim item As Shell32.FolderItem

Dim fol2 As Shell32.Folder

If Not fol Is Nothing Then

For Each item In fol.Items

    If item.IsFolder Then

        Set fol2 = item.GetFolder

        ProcessFolderRecursively fol2, row

    Else

       Sheets("Sheet2").Select

            Cells(row, 1) = item.path

            row = row + 1  
    End If

Next

End If

End Sub

Community
  • 1
  • 1
leadgen tool
  • 1
  • 1
  • 3
  • 1
    Help us to help you. **Post your current code.** – Gary's Student Jan 06 '17 at 15:16
  • http://s2.quickmeme.com/img/ea/ea3ef68e4af1492e6a026776d12dcc1ac032bd607dad9e3c6ed61992255dc876.jpg – CodeJockey Jan 06 '17 at 15:20
  • THe above code just looks for gets all folder path of the all the files. But i want it to be coded in such a way that it should search for the user keyword inside a text file and then retrieve the folder name and path that containing the text file. – leadgen tool Jan 06 '17 at 15:29

2 Answers2

0

i believe this answer will help you to answer your question.

Using a wildcard to open an excel workbook

In VBA you can not wildcard characters like * to open files. If the file names and locations do not change then you need to compile a list of all the file names.

You can then take the list, open each file in the list and scan the text doc with a find() function for the searched key word. if found then return the file name.

the issue you face is compiling the file locations to make the list, which i dont have an answer. the rest is easy.

Community
  • 1
  • 1
0

The following code could help you

Option Explicit
Public Function RecursiveDir(colFiles As Collection, _
                             strFolder As String, _
                             strFileSpec As String, _
                             bIncludeSubfolders As Boolean)

Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant

    'Add files in strFolder matching strFileSpec to colFiles
    strFolder = TrailingSlash(strFolder)
    strTemp = Dir(strFolder & strFileSpec)
    Do While strTemp <> vbNullString
        colFiles.Add strFolder & strTemp
        strTemp = Dir
    Loop

    If bIncludeSubfolders Then
        'Fill colFolders with list of subdirectories of strFolder
        strTemp = Dir(strFolder, vbDirectory)
        Do While strTemp <> vbNullString
            If (strTemp <> ".") And (strTemp <> "..") Then
                If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
                    colFolders.Add strTemp
                End If
            End If
            strTemp = Dir
        Loop

        'Call RecursiveDir for each subfolder in colFolders
        For Each vFolderName In colFolders
            Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
        Next vFolderName
    End If

End Function

Public Function TrailingSlash(strFolder As String) As String
    If Len(strFolder) > 0 Then
        If Right(strFolder, 1) = "\" Then
            TrailingSlash = strFolder
        Else
            TrailingSlash = strFolder & "\"
        End If
    End If
End Function

Function SearchTxtFile(ByVal txtFileName As String, txtSearch As String) As Boolean

Dim fso As Object 'Scripting.FileSystemObject
Dim myFile As Object 'Scripting.TextStream     
Dim ReadAllTextFile As Variant

    Set fso = CreateObject("Scripting.FileSystemObject")
    ' Open the file for input.
    Set myFile = fso.OpenTextFile(txtFileName, ForReading)

    ' Read from the file.
    If myFile.AtEndOfStream Then
        ReadAllTextFile = ""
    Else
        ReadAllTextFile = myFile.ReadAll
    End If

    If InStr(1, ReadAllTextFile, txtSearch, vbTextCompare) > 0 Then
        SearchTxtFile = True
    Else
        SearchTxtFile = False
    End If

End Function
Sub TestSearchFiles()

Dim colFiles As New Collection
Const txtPattern = "Business"
Const YOUR_START_DIR = "Your Dir"

    RecursiveDir colFiles, YOUR_START_DIR, "*.TXT", True

    Dim vFile As Variant
    For Each vFile In colFiles
        If SearchTxtFile(vFile, txtPattern) Then
            Debug.Print vFile
        End If
    Next vFile

End Sub

EDIT The following code will give the path name of a full path

Function GetDirectory(path)
   GetDirectory = Left(path, InStrRev(path, "\"))
End Function

Chhange the debug.print line in the code above to

Debug.Print vFile, GetDirectory(vFile)

Is that what you want?

EDIT2: Change the search function like that

Function SearchTxtFile(ByVal txtFileName As String, txtSearch() As Variant) As Boolean

Dim fso As Object    'Scripting.FileSystemObject
Dim myFile As Object    'Scripting.TextStream
Dim ReadAllTextFile As Variant
Dim i As Long

    Set fso = CreateObject("Scripting.FileSystemObject")
    ' Open the file for input.
    Set myFile = fso.OpenTextFile(txtFileName, ForReading)

    ' Read from the file.
    If myFile.AtEndOfStream Then
        ReadAllTextFile = ""
    Else
        ReadAllTextFile = myFile.ReadAll
    End If

    For i = LBound(txtSearch) To UBound(txtSearch)
        If InStr(1, ReadAllTextFile, txtSearch(i), vbTextCompare) > 0 Then
            SearchTxtFile = True
        Else
            SearchTxtFile = False
            ' If just one string is not found
            ' no further search neccessary
            Exit Function
        End If
    Next

End Function

Test it with

Sub TestSearchFiles()

Dim colFiles As New Collection
Dim txtPattern() As Variant
Const YOUR_START_DIR = "Your directory here"

    txtPattern = Array("Pattern1", "Pattern2")
    RecursiveDir colFiles, YOUR_START_DIR, "*.TXT", True

    Dim vFile As Variant
    For Each vFile In colFiles
        If SearchTxtFile(vFile, txtPattern) Then
            Debug.Print vFile, GetDirectory(vFile)
        End If
    Next vFile

End Sub
Storax
  • 11,158
  • 3
  • 16
  • 33
  • Excellent. Thank you very much for your help!. I works perfect for me – leadgen tool Jan 06 '17 at 16:04
  • One more quick question. How do i get the folder name instead of the text file name. And i need to display multiple folder names as a list in the excel sheet if there are more text files found in the different folders – leadgen tool Jan 06 '17 at 16:06
  • Excellent!. Thank you very much. And it would be of great help if you could also show me how to add multiple search keyword to look in the text file and retrieve the same if it found all the search keywords.Thanking you in advance – leadgen tool Jan 06 '17 at 17:16
  • Have a look at EDIT2 – Storax Jan 06 '17 at 17:46
  • That works perfect. Thank you once again. I tried testing the code in my shared folder, but i am not able to traverse completely throgh all of my folders and sub folders in my shared folder. I am getting file not found error in the midst. Is that because of more sub folders or are there any restriction in searching though lot of file and sub folders. – leadgen tool Jan 06 '17 at 22:16
  • I do have couple of case ware link files in some of the folders and i think the error is occurring just before accessing the case ware file. Is there any option that i could ignore case ware shortcut files from searching. – leadgen tool Jan 06 '17 at 22:21
  • I am afraid but I do not know what a "case ware link file" is so I won't be able to help you with that point. Question is where does the error excatly occur and what is the error message saying. Otherwise it will be difficult also for others to help you. – Storax Jan 07 '17 at 08:21
  • I am getting a Run-time error '53': File not found. – leadgen tool Jan 09 '17 at 15:50
  • I just run the code again now and its showing error wen it loops through a pdf file which has a pretty much big name – leadgen tool Jan 09 '17 at 15:58