• Search files for information contained in Excel cell and return path

    Home » Forums » AskWoody support » Productivity software by function » MS Excel and spreadsheet help » Search files for information contained in Excel cell and return path

    Author
    Topic
    #491053

    Hi,

    I have an Excel spreadsheet with a filename in column A. The filenames listed in column A appear in one or more Ms office .doc files in one or more source directories.

    I need Excel to search the .doc files recursively and return the path(s) of the file(s) that contain the filename specified in column A into column B. If more than one file go to column C etc.

    I have the macro which does the search file in folder and sub folder and list the path, I want path of those filename which appear in column A

    __|______A_____|______B_____|
    1 | test_1.doc |c:costtest_1.doc|
    2 | test_2.doc |c:costtest_2.doc|

    Downloaded from internet : This script does the search in folder & sub folder and returns the path of files.

    Code:
    Sub search() 
        Dim myDir As String, myList() 
        With Application.FileDialog(msoFileDialogFolderPicker) 
            If .Show = True Then 
                myDir = .SelectedItems(1) 
            End If 
        End With 
        On Error Resume Next 
        myList = SearchFiles(myDir, “*.doc”, 0, myList()) 
        If Err = 0 Then 
            Sheets(1).Cells(2).Resize(UBound(myList, 2), UBound(myList, 1)).Value = _ 
            Application.Transpose(myList) 
        Else 
            MsgBox “No file found” 
        End If 
        On Error Goto 0 
    End Sub 
      
    Private Function SearchFiles(myDir As String _ 
        , myFileName As String, n As Long, myList()) As Variant 
        Dim fso As Object, myFolder As Object, myFile As Object 
        Set fso = CreateObject(“Scripting.FileSystemObject”) 
        For Each myFile In fso.getfolder(myDir).Files 
            If (Not myFile.Name Like “~$*”) * (myFile.Name  ThisWorkbook.Name) _ 
            * (myFile.Name Like myFileName) Then 
                n = n + 1 
                Redim Preserve myList(1 To 2, 1 To n) 
                myList(1, n) = myDir & “” & myFile.Name 
                 End If 
        Next 
        For Each myFolder In fso.getfolder(myDir).subfolders 
            SearchFiles = SearchFiles(myFolder.Path, myFileName, n, myList) 
        Next 
        SearchFiles = IIf(n > 0, myList, “”) 
    End Function
    
    Viewing 7 reply threads
    Author
    Replies
    • #1413172

      Welcome to the Lounge

      If I understand your question the current Macro is working but it is showing the PATH and FILENAME in COL B, Col C, Etc.

      What you want is Col B, Col C, etc just to show the PATH.

      To do this you should change the following

      Current line myList(1, n) = myDir & “” & MyFileName
      New Line myList(1, n) = myDir & “”

      Hope this helps you issue.

      Regards,

      TD

      • #1413280

        Thanks for response, NO actually I need Excel to search the .doc files recursively and return the path(s) of the file(s) that contain the filename specified in column A
        I need to only have those path(s) whose filenames are in Column A.
        Hoping to have a positive reply.

        • #1413312

          Hi Shakir

          I believe what you are asking for is this:
          Starting with a chosen folder,
          ..for each file listed in column [A],
          ..list all folders which contain that file,
          ..using adjacent columns for each folder and subfolder the file is found in.

          If this is what you want, then my attached file does this.

          On completion of the search for the specified files, the column widths will be adjusted automatically to show the folder paths.

          You can adapt the routine as required.

          Please let me know if this does what you want.

          zeddy

          • #1413313

            Hi Shakir

            ..I originally thought your request was to search all documents in folders and subfolders for documents that ‘included’ the specified filename somewhere in the document!

            zeddy

            • #1413314

              Hi Shakir

              ..so what I think you are really asking for is to list all folders that contain ‘copies’ of specified files.

              zeddy

          • #1413326

            Please let me know if this does what you want.
            zeddy

            You are a genius, Thanks.
            Zeedy one problem with script on testing i found that if suppose a file name which is not there in the folder and it is listed in Column A then the script throws ‘No file found’ & for all descending list of Colum A whereas i have the other files inside the folder then to it.
            Please have a look to this issue.

            • #1413358

              Hi shakir

              ..try the attached next version..

              zeddy

            • #1413398

              Zeddy, Thanks for response, highly obliged.
              Zeddy, I want to have the filename along with path(s) right now it gives only path, i.e. c:paydaycosttest.doc ,this will be a complete search.
              Secondly if the extention of filenames to be searched in column A is not available it returns empty result whereas the files are in the folder. Please remove compulsory extention required in Col A.
              Once again thankyou.
              Hope to have a favourable response.

            • #1413768

              Hi Shakir

              ..I’ll try and post a solution tomorrow. I’ve been busy.

              zeddy

            • #1430971

              Hello,

              I am desperately in need of the codes which needs some changes, please help to get the results. The code fetchs the path and not the file name along the path in Col ‘B’ secondly if i don’t provide the extention in Col ‘A’ the search returns empty whereas the files are in the folder. Remove the compulsory extention part.

              Col-A_____Col-B
              test1.doc|c:paydaycosttest1.doc
              test5.doc|c:paydaycosttest5.doc
              test3.doc|c:paydaycosttest3.doc
              test6.doc|c:paydaycosttest6.doc
              test2.doc|:paydaycosttest2.doc

              Code:
              Private zList() As String
              
              Sub searchFiles()
              ‘Dim zPath As String
              
              With Application.FileDialog(msoFileDialogFolderPicker)  ‘use shortcut
              If .Show = True Then                ‘a folder has been chosen
              zStartFolder = .SelectedItems(1)    ‘folder to search;
              Else                                ‘otherwise..
              Exit Sub                            ‘..nothing else to do
              End If                              ‘end of test for folder selection
              End With                            ‘end of shortcut
              
              On Error Resume Next
              ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
              For Each cell In [a1:a100]          ‘loop through all entries in this defined range
              zFilename = cell.Value              ‘current file being sought
              zRow = cell.Row                     ‘row number of current file being sought
              
              If zFilename = “” Then              ‘reached end of list of filenames, so..
              Cells.EntireColumn.AutoFit          ‘..make all columns fit
              [a1].Select                         ‘put cellpointer in tidy location
              End                                 ‘all done; nothing else to do
              End If                              ‘end of test for empty filename cell
              
              ‘PROCEED WITH SEARCH FOR FILE..
              Erase zList                        ‘clear array for start of file search
              myFileSearch zStartFolder, zFilename, zIncludeSubFolders:=True, zCounter:=0
              
              zCount = UBound(zList)             ‘e.g. 4
              Sheets(1).Cells(zRow, 2).Resize(1, zCount).Value = zList
              Next                                ‘process with next filename in column [A]
              ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
              End Sub
              Private Sub myFileSearch(zPath, zFilename, zIncludeSubFolders As Boolean, zCounter As Long)
              
              Dim fso As Object, zSubFolder As Object, myFile As Object
              
              zFetch = zPath & “” & zFilename
              If Dir(zFetch)  “” Then
              zCounter = zCounter + 1
              ReDim Preserve zList(1 To zCounter)
              zList(zCounter) = zPath & “”
              End If
              
              If zIncludeSubFolders Then
              Set fso = CreateObject(“Scripting.FileSystemObject”)
              For Each zSubFolder In fso.GetFolder(zPath).Subfolders
              myFileSearch zPath & “” & zSubFolder.Name, zFilename, True, zCounter
              Next
              End If
              
              End Sub
              
    • #1431890

      Hi Shakir

      I believe what you are now asking for is this:
      Starting with a chosen folder,
      ..for each entry listed in column [A],
      ..list all folders which contain any file that includes the contents specified in col [A] within any filename,
      ..using adjacent columns for each folder and subfolder the file is found in.

      If this is what you want, then my attached file does this.

      On completion of the search for the specified files, the column widths will be adjusted automatically to show the folder paths.

      You can adapt the routine as required.

      Please let me know if this does what you want.

      ..And thank you doorjam1 for your Thanks. I hope you like this newer, flexible version

      zeddy

      • #1432063

        Hello,

        Many Thanks Zeddy, that’s perfect.

        Thanks.

    • #1439860

      Hi,

      This was a good one, thanks zeddy!

      Is it possible to write the results as hyperlinks? So one could open the file from excel with a single click.

      BR,
      DILiro

    • #1440315

      Zeddy, very sweet! I like the way you used an array

      DILiro

      You will need to add the three highlighted in blue lines to Zeddy’s code to create the hyperlinks

      Code:
      
      Private zList() As String
      
      Sub searchFiles()
      ‘Dim zPath As String
      
      With Application.FileDialog(msoFileDialogFolderPicker)  ‘use shortcut
      If .Show = True Then                ‘a folder has been chosen
      zStartFolder = .SelectedItems(1)    ‘folder to search;
      Else                                ‘otherwise..
      Exit Sub                            ‘..nothing else to do
      End If                              ‘end of test for folder selection
      End With                            ‘end of shortcut
      
      On Error Resume Next
      
      ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      For Each cell In [a1:a100]          ‘loop through all entries in this defined range
      zFilename = cell.Value              ‘current file being sought
      zRow = cell.Row                     ‘row number of current file being sought
      
      If zFilename = “” Then              ‘reached end of list of filenames, so..
      Cells.EntireColumn.AutoFit          ‘..make all columns fit
      [a1].Select                         ‘put cellpointer in tidy location
      End                                 ‘all done; nothing else to do
      End If                              ‘end of test for empty filename cell
      
      ‘PROCEED WITH SEARCH FOR FILE..
      Erase zList                        ‘clear array for start of file search
      myFileSearch zStartFolder, zFilename, zIncludeSubFolders:=True, zCounter:=0
      
      zCount = UBound(zList)             ‘e.g. 4
      Sheets(1).Cells(zRow, 2).Resize(1, zCount).Value = zList
      [COLOR=”#0000FF”]For I = 2 To zCount + 1 
          ActiveSheet.Hyperlinks.Add Cells(zRow, I), Cells(zRow, I) 
      Next I [/COLOR]
      Next                                ‘process with next filename in column [A]
      ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      
      End Sub
      
      
      Private Sub myFileSearch(zPath, zFilename, zIncludeSubFolders As Boolean, zCounter As Long)
      
      Dim fso As Object, zSubFolder As Object, myFile As Object
      Dim zFolder As Object
      
      If Right(zPath, 1)  “” Then zPath = zPath & “”
      
      zMask = “*” & zFilename & “*”
      zSearch = Dir(zPath & zMask)
      
      Do While Len(zSearch) > 0
      zCounter = zCounter + 1
      ReDim Preserve zList(1 To zCounter)
      zList(zCounter) = zPath & zSearch
      zSearch = Dir
      Loop
      
      If zIncludeSubFolders Then
      Set fso = CreateObject(“Scripting.FileSystemObject”)
      For Each zSubFolder In fso.GetFolder(zPath).Subfolders
      myFileSearch zPath & zSubFolder.Name, zFilename, True, zCounter
      Next
      End If
      
      End Sub
      
      
      • #1440513

        Hi Maud

        ..thanks for fixing the file for hyperlinks.

        I’ve been to London and just got back yesterday.

        zeddy

    • #1440628

      NP, my friend

    • #1446721

      hey zeddy,
      your code is very good, but i need a modification that, i just want the name of the subfolder were the file is not the whole path.

      • #1448567

        Hi

        My code searches for filenames that contain the text entered in column [A], and the search results include the full path to the file.
        If more than one file is found that contains the specified text, the found files are shown in adjacent columns.

        Now it may be that for a particular text string, e.g. “fred”, there could be several files within the same folder that match, e.g. “letter to fred.doc”, “fred expenses.xls”, “Manfred-mann.mp3″ etc etc, so if you wanted the subfolder only, this would mean that the subfolder would be repeated for every file that included the search string. So the code would need additional modifications to remove these unnecessary repeats of the same folder.

        zeddy

    • #1446722

      hey zeddy, there is problem in the code, if run it second time or more and now the same file which was in folder 1 and now it is in folder 2 , then it does not update the path.

    • #1448961

      thank you for your explaination,
      i want a very little modification, instead of whole hyperlinked path, i need the name of the file (hyperlinked)

    Viewing 7 reply threads
    Reply To: Search files for information contained in Excel cell and return path

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: