Get the list of files from a folder based on cell A1

Lakabi

New Member
Joined
Jun 11, 2011
Messages
26
Hi all
I would like to have to have the list of files from folder "X" including subfolders ( the folder is on the network), in column B, and from folder "Y" including subfolders ( the folder is on the network) in column C based on the criteria in cell A1. I am looking for all files which names starts with the string entered in A1. Ex. if A1= 12345, then list all files from folder X and folder Y, which file names start with 12345 (ex file "12345 abc.pdf"). Perhaps list only the file names as hyperlinks. Also I would need the list to update soon as the value or string in A1 is changed. Using Excel 2003.
Thanks in advance.
 
Thanks for the review and correction.
Also any ideas how to run the macro when the value changes in cell B1?

Code:
Function CreateFileList(FileFilter As String, _
    IncludeSubfolders As Boolean) As Variant
' returns the full filename for files matching
' the filter criteria in the current folder
Dim FileList() As String, FileCount As Long
    CreateFileList = ""
    Erase FileList
    If FileFilter = "*.*" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = CurDir
        .FileName = FileFilter
        .SearchSubFolders = IncludeSubfolders
        .FileType = msoFileTypeAllFiles
        If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) = 0 Then Exit Function
        ReDim FileList(.FoundFiles.Count)
        For FileCount = 1 To .FoundFiles.Count
            FileList(FileCount) = .FoundFiles(FileCount)
        Next FileCount
        .FileType = msoFileTypeExcelWorkbooks ' reset filetypes
    End With
    CreateFileList = FileList
    Erase FileList
End Function

Sub TestCreateFileList()
Dim FileNamesList As Variant, i As Integer
    ChDir "C:\Documents and Settings\User\My Documents"
    ' activate the desired startfolder for the filesearch
    FileNamesList = CreateFileList(Range("B1").Value & "*.*", True)
    ' performs the filesearch, includes any subfolders
    ' present the result
    Range("A:A").ClearContents
    For i = 1 To UBound(FileNamesList)
        Cells(i + 1, 1).Formula = FileNamesList(i)
    Next i
End Sub
 
Upvote 0

Excel Facts

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop
Add this to the Worksheet code module.

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$1" Then
        Call TestCreateFileList
    End If
End Sub

FYI
Worksheet code module can be accessed by
  • Opening VBA Editor (alt+F11)
  • In Project Explorer Pane (Ctrl+R) if not visible.
  • Double click on sheet of interest of interest
  • Paste
 
Upvote 0
Thanks. Works nice. How do I extend the search into two separate folders.
Like:cell B1 is still reference but list files from folder A (and sub folders) in column A and folder B (and subfolders) in column B.
 
Upvote 0
Here is what I came up with. Is there a simpler code to do this?

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$1" Then
        Call TestCreateFileList
        Call TestCreateFileList2
    End If
End Sub

Function CreateFileList(FileFilter As String, _
    IncludeSubfolders As Boolean) As Variant
' returns the full filename for files matching
' the filter criteria in the current folder
Dim FileList() As String, FileCount As Long
    CreateFileList = ""
    Erase FileList
    If FileFilter = "*.*" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = CurDir
        .FileName = FileFilter
        .SearchSubFolders = IncludeSubfolders
        .FileType = msoFileTypeAllFiles
        If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) = 0 Then Exit Function
        ReDim FileList(.FoundFiles.Count)
        For FileCount = 1 To .FoundFiles.Count
            FileList(FileCount) = .FoundFiles(FileCount)
        Next FileCount
        .FileType = msoFileTypeExcelWorkbooks ' reset filetypes
    End With
    CreateFileList = FileList
    Erase FileList
End Function

Sub TestCreateFileList()
Dim FileNamesList As Variant, i As Integer
    ChDir "C:\Documents and Settings\User\My Documents"
    ' activate the desired startfolder for the filesearch
    FileNamesList = CreateFileList(Range("B1").Value & "*.*", True)
    ' performs the filesearch, includes any subfolders
    ' present the result
    Range("A:A").ClearContents
    For i = 1 To UBound(FileNamesList)
        Cells(i + 1, 1).Formula = FileNamesList(i)
    Next i
End Sub


Function CreateFileList2(FileFilter As String, _
    IncludeSubfolders As Boolean) As Variant
' returns the full filename for files matching
' the filter criteria in the current folder
Dim FileList2() As String, FileCount As Long
    CreateFileList2 = ""
    Erase FileList2
    If FileFilter = "*.*" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = CurDir
        .FileName = FileFilter
        .SearchSubFolders = IncludeSubfolders
        .FileType = msoFileTypeAllFiles
        If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) = 0 Then Exit Function
        ReDim FileList2(.FoundFiles.Count)
        For FileCount = 1 To .FoundFiles.Count
            FileList2(FileCount) = .FoundFiles(FileCount)
        Next FileCount
        .FileType = msoFileTypeExcelWorkbooks ' reset filetypes
    End With
    CreateFileList2 = FileList2
    Erase FileList2
    
End Function


Sub TestCreateFileList2()
Dim FileNamesList2 As Variant, i As Integer
    ChDir "C:\Documents and Settings\User\My Documents"
    ' activate the desired startfolder for the filesearch
    FileNamesList2 = CreateFileList2(Range("B1").Value & "*.*", False)
    ' performs the filesearch, includes any subfolders
    ' present the result
    Range("C:C").ClearContents
    For i = 1 To UBound(FileNamesList2)
        Cells(i + 1, 3).Formula = FileNamesList2(i)
    Next i
End Sub
Also I am using In cell I2 down to I... the function =HYPERLINK(A2) and so on, to create a the shortcut to the file, but I would like the file name to appear only as the link, instead of the full path.
Thanks in advance.
 
Upvote 0
Without getting too complicated with the Hyperlink you can just use
Code:
=HYPERLINK(A2,SUBSTITUTE(A2,"C:\Documents and Settings\User\My Documents\",""))
It will get rid of the C:\Documents and Settings\User\My Documents\ but leave the sub folders.

The code can be simplified if the Sub has parameters like the following:
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$1" Then
        TestCreateFileList Target.Value, "A", True
        TestCreateFileList Target.Value, "C", False
    End If
End Sub

Sub TestCreateFileList(criteria As String, OuputCol As String, _
                        IncludeSubfolders As Boolean)
    Dim FileNamesList As Variant, i As Integer
    ChDir "C:\Documents and Settings\User\My Documents"
    ' activate the desired startfolder for the filesearch
    FileNamesList = CreateFileList(criteria & "*.*", IncludeSubfolders)
    ' performs the filesearch, includes any subfolders
    ' present the result
    Columns(OutputCol).ClearContents
    For i = 1 To UBound(FileNamesList)
        Cells(i + 1, Columns(OutputCol).Column).Formula = FileNamesList(i)
    Next i
End Sub

Function CreateFileList(FileFilter As String, _
    IncludeSubfolders As Boolean) As Variant
' returns the full filename for files matching
' the filter criteria in the current folder
Dim FileList() As String, FileCount As Long
    CreateFileList = ""
    Erase FileList
    If FileFilter = "*.*" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = CurDir
        .Filename = FileFilter
        .SearchSubFolders = IncludeSubfolders
        .FileType = msoFileTypeAllFiles
        If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) = 0 Then Exit Function
        ReDim FileList(.FoundFiles.Count)
        For FileCount = 1 To .FoundFiles.Count
            FileList(FileCount) = .FoundFiles(FileCount)
        Next FileCount
        .FileType = msoFileTypeExcelWorkbooks ' reset filetypes
    End With
    CreateFileList = FileList
    Erase FileList
End Function

Untested
 
Upvote 0
Thanks,

Hyperlinks works, but because of the subfolders, the subolders will still show up in the link (after "Mydocuments\" as you posted.

On the macro I got "error 1004" at line:

Code:
Columns(OutputCol).ClearContents
in the sub:

Code:
Sub TestCreateFileList(criteria As String, OuputCol As String, _
                        IncludeSubfolders As Boolean)
    Dim FileNamesList As Variant, i As Integer
    ChDir "C:\Documents and Settings\User\My Documents"
    ' activate the desired startfolder for the filesearch
    FileNamesList = CreateFileList(criteria & "*.*", IncludeSubfolders)
    ' performs the filesearch, includes any subfolders
    ' present the result
    Columns(OutputCol).ClearContents
    For i = 1 To UBound(FileNamesList)
        Cells(i + 1, Columns(OutputCol).Column).Formula = FileNamesList(i)
    Next i
End Sub
Thank you for looking into it.
 
Last edited:
Upvote 0
I didn't test it so I missed a typo I made. Change the highlighted text

Code:
Sub TestCreateFileList(criteria As String, [COLOR="Red"][B]OuputCol [/B][/COLOR]As String, _
                        IncludeSubfolders As Boolean)

OuputCol should be OutputCol

For the hyperlinks try this macro. It will prompt you for the source column and destination column just select any cell in the desired columns.
Code:
Sub MakeLink()
    Dim cell As Range
    Dim PathRng As Range
    
    Dim LinkLoc As String
    Dim LinkTxt As String
    
    Dim outputCol As Integer
    Dim colOffset As Integer
    
    Set PathRng = Application.InputBox( _
                    Prompt:="Select Column of containing paths.", _
                    Type:=8)
    
    Set PathRng = Intersect(ActiveSheet.UsedRange, _
            Range(Cells(2, PathRng.Column), Cells(Rows.Count, PathRng.Column)))
    
    outputCol = Application.InputBox( _
                    Prompt:="Select Column to output Hyperlinks.", _
                    Type:=8).Column
    
    Range(Cells(2, outputCol), Cells(Rows.Count, outputCol)).ClearContents
    
    colOffset = outputCol - PathRng.Column
    
    For Each cell In PathRng
        LinkLoc = cell.Value
        LinkTxt = Mid(LinkLoc, InStrRev(LinkLoc, "\") + 1)
       
          ActiveSheet.Hyperlinks.Add _
            Anchor:=cell.Offset(0, colOffset), _
            Address:=LinkLoc, _
            TextToDisplay:=LinkTxt
    Next cell
End Sub
 
Upvote 0
Thanks.
The code works very nice. I am just confused, how can I change the search directory separately. Ex C:\folder1 (to list in column A) and C:\folder2 (to list in column C). Also when I am trying to pinpoint a folder on my network, I had an error message once (sorry did not record the message), then most of the time defaults back to "MyDocuments".
The "Hyperlink" macro is very clever (elegant). I just have to re run it every time when the value changed in cell "B1".
My ultimate goal when I type the "Item" in "B1", all related files which starts with the "item" will list form "folder1" in column "A" and lists the files from from "folder2" in column "C". Eventually I will need two other lists from two other folders, with the difference that the "item" is buried inside the file name (the files did not start with "item').
This way looking up the "item" will have a list of related files in four different category.
Thanks again.
 
Upvote 0
The following should get you closer to your goal. I made it so you can specify all the variable arguments in one call. The hyperlink column can be excluded if you don't need it but can be include if you want to generate the hyperlinks. There is also some added error handling. You will still need Function CreateFileList but everything else can be replaced with below.
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B$1" Then
    '
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("B1").Value, _
                    SearchPath:="C:\Test", _
                    IncludeSubfolders:=True, _
                    OutputCol:="A", _
                    HyperlinkCol:="I"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("B1").Value, _
                    SearchPath:="C:\Test1", _
                    IncludeSubfolders:=False, _
                    OutputCol:="C", _
                    HyperlinkCol:="J"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("B1").Value, _
                    SearchPath:="C:\Test2", _
                    IncludeSubfolders:=False, _
                    OutputCol:="D", _
                    HyperlinkCol:="K"
                      
    End If
End Sub
Code:
Sub TestCreateFileListAndHyperlinks( _
                Criteria As String, _
                SearchPath As String, _
                IncludeSubfolders As Boolean, _
                OutputCol As String, _
                Optional HyperlinkCol As String)
                
    Dim FileNamesList As Variant
    Dim startDir As String
    Dim oCol As Integer
    Dim hCol As Integer
    Dim i As Integer
    Dim addHL As Boolean
    '// ———————————————————————————————————————————————————————————————————————
    '// Check if directory exists
    If Dir(SearchPath, vbDirectory) = "" Then
        MsgBox "PATH:" & SearchPath & " — doesn't exist or is not accessible"
        Exit Sub
    End If
    If Not IsMissing(HyperlinkCol) And HyperlinkCol <> "" Then addHL = True
    oCol = Columns(OutputCol).Column
    If addHL Then hCol = Columns(HyperlinkCol).Column
    '// ———————————————————————————————————————————————————————————————————————
    '// Directory and File Search Operations
    '//
    '// Store the Current Directory
    startDir = CurDir()
    '// Set the search directory
    ChDir SearchPath
    '// Create file list that matches Criteria with seperate Function
    FileNamesList = CreateFileList(Criteria & "*.*", IncludeSubfolders)
    '// Restore current current Directory to previous path
    ChDir startDir
    
    '// ———————————————————————————————————————————————————————————————————————
    '// Clear Contents of Output Row Excluding First Row
    Range(Cells(2, oCol), Cells(Rows.Count, oCol)).ClearContents
    If addHL Then Range(Cells(2, hCol), Cells(Rows.Count, hCol)).ClearContents
    
    '// ———————————————————————————————————————————————————————————————————————
    '// Results Output
    '//
    '// Set Default value if criteria was not found in search folder
    '//  will be overwritten if criteria finds match
    Cells(2, Columns(OutputCol).Column).Formula = "No Match to Criteria"
    '// Error handling to prevent errors if array is empty
    On Error Resume Next
    For i = 1 To UBound(FileNamesList)
        '// Path Output
        Cells(i + 1, oCol).Formula = FileNamesList(i)
       If addHL Then
        '// Hyperlink Output
        ActiveSheet.Hyperlinks.Add _
            Anchor:=Cells(i + 1, hCol), _
            Address:=FileNamesList(i), _
            TextToDisplay:= _
                Mid(FileNamesList(i), InStrRev(FileNamesList(i), "\") + 1)
        End If
    Next i
    On Error GoTo 0
End Sub
 
Upvote 0
This is VERY GOOD. I like that is easy to add additional folders to search. Clever. THANKS.
Just realized having the hyperlinks only (without the separate list) would be more useful, since I will have the list of files anyhow, with quick access to them. Can you please modify the code?
Also since expected number of files would be 15 or less, can you restrict the "clear columns" for 30 cells down only? I would like to use the cells below the list, but all cells below the hyperlinks, clears every time I enter a new value in the reference cell.
The other question, since the criteria for the list is all the files that names starts with the string from cell "B1", I would like to extend into two additional folder, for files which contains the string from cell "B1". Ex. B1=ab12, it would list all files, which names contain "ab12" in any form.

The code works very good, but I have not tested yet with folders on my network.

For the people who is following this post, here is the code I have modified to start to incorporate the code into my actual working sheet (it is not final just testing). I added the fourth folder to search, moved the reference cell to "A1", moved the Hyperlinks to column B,C,D and E, and starting row to "Row3". Also moved away the output file list into column X,Y,Z and AA, since at this point I am not using it.
Since it is working I do not think that I made a mistake in the modification. True?

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
    '
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="C:\TEST1", _
                    IncludeSubfolders:=True, _
                    OutputCol:="X", _
                    HyperlinkCol:="B"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="C:\TEST2", _
                    IncludeSubfolders:=True, _
                    OutputCol:="Y", _
                    HyperlinkCol:="C"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="C:\TEST3", _
                    IncludeSubfolders:=True, _
                    OutputCol:="Z", _
                    HyperlinkCol:="D"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="C:\TEST4", _
                    IncludeSubfolders:=True, _
                    OutputCol:="AA", _
                    HyperlinkCol:="E"
    End If
End Sub



Sub TestCreateFileListAndHyperlinks( _
                Criteria As String, _
                SearchPath As String, _
                IncludeSubfolders As Boolean, _
                OutputCol As String, _
                Optional HyperlinkCol As String)
                
    Dim FileNamesList As Variant
    Dim startDir As String
    Dim oCol As Integer
    Dim hCol As Integer
    Dim i As Integer
    Dim addHL As Boolean
    '// ———————————————————————————————————————————————————————————————————————
    '// Check if directory exists
    If Dir(SearchPath, vbDirectory) = "" Then
        MsgBox "PATH:" & SearchPath & " — doesn't exist or is not accessible"
        Exit Sub
    End If
    If Not IsMissing(HyperlinkCol) And HyperlinkCol <> "" Then addHL = True
    oCol = Columns(OutputCol).Column
    If addHL Then hCol = Columns(HyperlinkCol).Column
    '// ———————————————————————————————————————————————————————————————————————
    '// Directory and File Search Operations
    '//
    '// Store the Current Directory
    startDir = CurDir()
    '// Set the search directory
    ChDir SearchPath
    '// Create file list that matches Criteria with seperate Function
    FileNamesList = CreateFileList(Criteria & "*.*", IncludeSubfolders)
    '// Restore current current Directory to previous path
    ChDir startDir
    
    '// ———————————————————————————————————————————————————————————————————————
    '// Clear Contents of Output Row Excluding First Row
    Range(Cells(3, oCol), Cells(Rows.Count, oCol)).ClearContents
    If addHL Then Range(Cells(3, hCol), Cells(Rows.Count, hCol)).ClearContents
    
    '// ———————————————————————————————————————————————————————————————————————
    '// Results Output
    '//
    '// Set Default value if criteria was not found in search folder
    '//  will be overwritten if criteria finds match
    Cells(3, Columns(OutputCol).Column).Formula = "No Match to Criteria"
    '// Error handling to prevent errors if array is empty
    On Error Resume Next
    For i = 1 To UBound(FileNamesList)
        '// Path Output
        Cells(i + 2, oCol).Formula = FileNamesList(i)
       If addHL Then
        '// Hyperlink Output
        ActiveSheet.Hyperlinks.Add _
            Anchor:=Cells(i + 2, hCol), _
            Address:=FileNamesList(i), _
            TextToDisplay:= _
                Mid(FileNamesList(i), InStrRev(FileNamesList(i), "\") + 1)
        End If
    Next i
    On Error GoTo 0
End Sub


Function CreateFileList(FileFilter As String, _
    IncludeSubfolders As Boolean) As Variant
' returns the full filename for files matching
' the filter criteria in the current folder
Dim FileList() As String, FileCount As Long
    CreateFileList = ""
    Erase FileList
    If FileFilter = "*.*" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = CurDir
        .Filename = FileFilter
        .SearchSubFolders = IncludeSubfolders
        .FileType = msoFileTypeAllFiles
        If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) = 0 Then Exit Function
        ReDim FileList(.FoundFiles.Count)
        For FileCount = 1 To .FoundFiles.Count
            FileList(FileCount) = .FoundFiles(FileCount)
        Next FileCount
        .FileType = msoFileTypeExcelWorkbooks ' reset filetypes
    End With
    CreateFileList = FileList
    Erase FileList
End Function
Thank you again for your time.
 
Upvote 0

Forum statistics

Threads
1,224,530
Messages
6,179,373
Members
452,907
Latest member
Roland Deschain

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top