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.
 
Let back up as I get the impression that the you probably don't need the criteria and folders to be that flexible and making it that flexible will actually make thing more complicated. If you only need the first two folders Z:\Seagate & C:\Folder2 to search the Prefix and the last two C:\Folder3 & C:\Folder4 to search in the file name then this would work.

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="Z:\Seagate", _
                    IncludeSubfolders:=True, _
                    OutputCol:="B", _
                    HyperlinkCol:="B"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="C:\FOLDER2", _
                    IncludeSubfolders:=True, _
                    OutputCol:="C", _
                    HyperlinkCol:="C"
        TestCreateFileListAndHyperlinks _
                    Criteria:=[COLOR="Red"][B]"*" & [/B][/COLOR]Range("A1").Value, _
                    SearchPath:="C:\FOLDER3", _
                    IncludeSubfolders:=True, _
                    OutputCol:="D", _
                    HyperlinkCol:="D"
        TestCreateFileListAndHyperlinks _
                    Criteria:=[COLOR="Red"][B]"*" & [/B][/COLOR]Range("A1").Value, _
                    SearchPath:="C:\FOLDER4", _
                    IncludeSubfolders:=True, _
                    OutputCol:="E", _
                    HyperlinkCol:="E"
    End If
End Sub

And change the 3 to a 2 on this line of Sub TestCreateFileListAndHyperlinks(...)
Code:
    '// Output Range
    '// First output Row
    Const START_ROW = [COLOR="Red"][B]3[/B][/COLOR]

Thoughts?
 
Upvote 0

Excel Facts

What is the shortcut key for Format Selection?
Ctrl+1 (the number one) will open the Format dialog for whatever is selected.
Yes this is it. It is flexible enough to add additional list with the criteria that I need now.

Far as changing number 3 to 2, I did not quite understand, since I could not find the lines you were referring too:
Code:
     '// Output Range   
     '// First output Row
     Const START_ROW = [COLOR=Red][B]3[/B][/COLOR]
Here is the complete code I have:

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
    '
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="Z:\Seagate", _
                    IncludeSubfolders:=True, _
                    OutputCol:="B", _
                    HyperlinkCol:="B"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value, _
                    SearchPath:="C:\Folder2", _
                    IncludeSubfolders:=True, _
                    OutputCol:="C", _
                    HyperlinkCol:="C"
        TestCreateFileListAndHyperlinks _
                    Criteria:="*" & Range("A1").Value, _
                    SearchPath:="Z:\Foder3", _
                    IncludeSubfolders:=True, _
                    OutputCol:="D", _
                    HyperlinkCol:="D"
        TestCreateFileListAndHyperlinks _
                    Criteria:="*" & Range("B1").Value, _
                    SearchPath:="C:\Folder4", _
                    IncludeSubfolders:=True, _
                    OutputCol:="E", _
                    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 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
    '//
    '// Create file list that matches Criteria with seperate Function
    FileNamesList = CreateFileList(Criteria & "*.*", SearchPath, IncludeSubfolders)
    
    '// ———————————————————————————————————————————————————————————————————————
    '// Clear Contents of Output Row Excluding First Row
    '// Clear Contents of Output Row Excluding First Row
    Range(Cells(2, oCol), Cells(30, oCol)).ClearContents
    If addHL And oCol <> hCol Then _
        Range(Cells(2, hCol), Cells(30, 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


Function CreateFileList( _
                    FileFilter As String, _
                    SearchFolder As String, _
                    IncludeSubfolders As Boolean) As Variant
' returns the full filename for files matching
' the filter criteria in the passed folder
Dim FileList() As String, FileCount As Long
    CreateFileList = ""
    Erase FileList
    If FileFilter = "*.*" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = SearchFolder
        .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
Please advise.

I have implemented completely in my working sheet, but as a stand alone is very good!
For the people who following this thread: the listing of files, searching thru thousands of files is done in about 2-3 seconds over the network.
Since this is working so well, I am wondering if you can add a list of files (these would be only excel files) that has the same string in cell C4.

I do thank you for all the help, and patience.
 
Upvote 0
In all the back and forth you are using an older version of the main function. I repost it and with the changes that are necessary to do file type search, highlighted in red.

Code:
Sub TestCreateFileListAndHyperlinks( _
                Criteria As String, _
                SearchPath As String, _
                IncludeSubfolders As Boolean, _
                OutputCol As Variant, _
                Optional HyperlinkCol As Variant)
                
    Dim FileNamesList As Variant
    Dim oCol As Integer         'Text Output Column Number
    Dim hCol As Integer         'Hyperlink Output Column
    Dim i As Integer            'Loop Counter
    Dim addHL As Boolean        'Hyperlink column passed
    '// ———————————————————————————————————————————————————————————————————————
    '// Output Range
    '// First output Row
    [COLOR="Blue"]Const START_ROW = 2[/COLOR]
    '// Clear to row
    Const LAST_ROW = 30
    '// ———————————————————————————————————————————————————————————————————————
    '// Output column
    oCol = Columns(OutputCol).Column
    '// Hyperlink column
    If Not IsMissing(HyperlinkCol) And HyperlinkCol <> "" Then addHL = True
    If addHL Then hCol = Columns(HyperlinkCol).Column
    '// ———————————————————————————————————————————————————————————————————————
    '// Directory and File Search Operations
    '//
    '// Create file list that matches Criteria with seperate Function
[COLOR="red"]    FileNamesList = CreateFileList(Criteria, SearchPath, IncludeSubfolders)
[/COLOR]    '// ———————————————————————————————————————————————————————————————————————
    '// Clear Contents of Output Row Excluding First Row
    Range(Cells(START_ROW, oCol), Cells(LAST_ROW, oCol)).ClearContents
    If addHL And oCol <> hCol Then _
        Range(Cells(START_ROW, hCol), Cells(LAST_ROW, hCol)).ClearContents
    '// ———————————————————————————————————————————————————————————————————————
    '// Check if directory exists
    If Dir(SearchPath, vbDirectory) = "" Then
        MsgBox SearchPath & vbCr & vbCr & "Doesn't exist or is not accessible"
        Exit Sub
    End If
    '// ———————————————————————————————————————————————————————————————————————
    '// Results Output
    '//
    '// Set Default value if criteria was not found in search folder
    '//  will be overwritten if criteria finds match
    Cells(START_ROW, Columns(OutputCol).Column).Formula = "No Criteria Match"
    '// Error handling to prevent errors if array is empty
    On Error Resume Next
    For i = 1 To UBound(FileNamesList)
        '// Path Output
        If oCol <> hCol Then
            Cells(i + 1, oCol).Formula = FileNamesList(i)
        End If
       If addHL Then
        '// Hyperlink Output
        ActiveSheet.Hyperlinks.Add _
            Anchor:=Cells((i - 1) + START_ROW, hCol), _
            Address:=FileNamesList(i), _
            TextToDisplay:= _
                Mid(FileNamesList(i), InStrRev(FileNamesList(i), "\") + 1)
        End If
    Next i
    On Error GoTo 0
End Sub

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
    '
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value[COLOR="red"] & "*.*"[/COLOR], _
                    SearchPath:="Z:\Seagate", _
                    IncludeSubfolders:=True, _
                    OutputCol:="B", _
                    HyperlinkCol:="B"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value[COLOR="red"] & "*.*"[/COLOR], _
                    SearchPath:="C:\Folder2", _
                    IncludeSubfolders:=True, _
                    OutputCol:="C", _
                    HyperlinkCol:="C"
        TestCreateFileListAndHyperlinks _
                    Criteria:="*" & Range("A1").Value[COLOR="red"] & "*.*"[/COLOR], _
                    SearchPath:="Z:\Foder3", _
                    IncludeSubfolders:=True, _
                    OutputCol:="D", _
                    HyperlinkCol:="D"
        TestCreateFileListAndHyperlinks _
                    Criteria:="*" & Range("B1").Value[COLOR="red"] & "*.*"[/COLOR], _
                    SearchPath:="C:\Folder4", _
                    IncludeSubfolders:=True, _
                    OutputCol:="E", _
                    HyperlinkCol:="E"
    End If
End Sub

Not sure what you mean by
Since this is working so well, I am wondering if you can add a list of files (these would be only excel files) that has the same string in cell C4.
as C4 is in the output range and its value will vary based on the what is in Folder2. What folder is it to search and where is its output?
 
Upvote 0
First, I could not post earlier. I had an family emergency.

Ran the new code, looks very good.

Far as the new request: what I was asking for the list of excel files that "sheet1" cell C4 contains a string that matches the string in A1.
I/O would be the same, just one of the lookup criteria would change.

Ex:
if file File1.xls "sheet1" cell "C4=abc"
and
file File2.xls "sheet1" cell"C4=bde"
then the list of files is
File1.xls
if A1=abc
or
File2.xls
if A1=bde

Can it be incorporated in the code above or should be a separate code?
Hope that I did explained it better.
 
Upvote 0
I think I know what you need but it been a long hot day so I might be off the marks. So here is what I understand your requirements to be.

In a similar manner as the previous problem create a list of files that match a given name criteria. This list is then parsed to include only Excel 'xls' files. {or is it all the xls files in given directory with no name criteria?}
Then parsed to include only the files that have a specified value in Cell Location [C4] on the Sheet Named "Sheet1".

Is that a fair rephrasing of you requirements?

Thanks
 
Upvote 0
Assuming that I understood your requirements correctly the following should very well work. It is similar to the previous code but has some added code to check the contents of the various workbooks. This will conflict with the previous code so place it in another worksheet or workbook.

Minor modification will be needed to get to work with the File name filter criteria and the cell C4 content filter. Right now it does all xls files in the provided directory and filter on C4 content based on criteria in A1. It does not filter on file names.

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
    If Target.Address = "$A$1" Then
        FilterXLS _
            Criteria:="*.xls", _
            SearchPath:="Z:\Seagate", _
            wsToCheck:="Sheet1", _
            CellToCheck:="C4", _
            ValueToMatch:=Range("A1").Value, _
            IncludeSubfolders:=True, _
            OutputCol:="B", _
            HyperlinkCol:="B"
'// ^^ Repeat for other folders as needed  ^^
    End If
Application.EnableEvents = True
End Sub

Code:
Sub FilterXLS( _
                Criteria As String, _
                SearchPath As String, _
                wsToCheck As String, _
                CellToCheck As String, _
                ValueToMatch As String, _
                IncludeSubfolders As Boolean, _
                OutputCol As Variant, _
                Optional HyperlinkCol As Variant)
                
    Dim FileNamesList As Variant
    Dim oCol As Integer         'Text Output Column Number
    Dim hCol As Integer         'Hyperlink Output Column
    Dim i As Integer            'Loop Counter
    Dim iRow As Long            'Output row tracking
    Dim addHL As Boolean        'Hyperlink column passed
    Dim wbPath As String
    Dim wbName As String
    Dim sFile As String
    Dim ValueFromWB As String
    
    '// ———————————————————————————————————————————————————————————————————————
    '// Output Range
    '// First output Row
    Const START_ROW = 2
    '// Clear to row
    Const LAST_ROW = 30
    '// ———————————————————————————————————————————————————————————————————————
    '// Output column
    oCol = Columns(OutputCol).Column
    '// Hyperlink column
    If Not IsMissing(HyperlinkCol) And HyperlinkCol <> "" Then addHL = True
    If addHL Then hCol = Columns(HyperlinkCol).Column
    '// ———————————————————————————————————————————————————————————————————————
    '// Directory and File Search Operations
    '// Create file list that matches Criteria with seperate Function
    FileNamesList = CreateFileList(Criteria, SearchPath, IncludeSubfolders)
    '// ———————————————————————————————————————————————————————————————————————
    '// Clear Contents of Output Row Excluding First Row
    Range(Cells(START_ROW, oCol), Cells(LAST_ROW, oCol)).ClearContents
    If addHL And oCol <> hCol Then _
        Range(Cells(START_ROW, hCol), Cells(LAST_ROW, hCol)).ClearContents
    '// ———————————————————————————————————————————————————————————————————————
    '// Check if directory exists
    If Dir(SearchPath, vbDirectory) = "" Then
        MsgBox SearchPath & vbCr & vbCr & "Doesn't exist or is not accessible"
        Exit Sub
    End If
    '// ———————————————————————————————————————————————————————————————————————
    '// Results Output
    '//
    '// Set Default value if criteria was not found in search folder
    '//  will be overwritten if criteria finds match
    Cells(START_ROW, Columns(OutputCol).Column).Formula = "No Criteria Match"
    '// Error handling to prevent errors if array is empty
    On Error Resume Next
    For i = LBound(FileNamesList) To UBound(FileNamesList)
        sFile = FileNamesList(i)
        wbPath = Left(sFile, InStrRev(sFile, "\"))
        wbName = Mid(sFile, InStrRev(sFile, "\") + 1)
        '// Get the value in cell of closed work
        ValueFromWB = GetInfoFromClosedFile(wbPath, wbName, wsToCheck, CellToCheck)
        '// Compare the value in cell in closed work to value to match
        If UCase(ValueFromWB) = UCase(ValueToMatch) Then
            '// Path Output
            If oCol <> hCol Then
                Cells(i + 1, oCol).Formula = sFile
            End If
            If addHL Then
            '// Hyperlink Output
            ActiveSheet.Hyperlinks.Add _
                Anchor:=Cells(iRow + START_ROW, hCol), _
                Address:=sFile, _
                TextToDisplay:=wbName
            End If
            iRow = iRow + 1
        End If
    Next i
    On Error GoTo 0
End Sub

Code:
Private Function GetInfoFromClosedFile( _
            ByVal wbPath As String, _
            wbName As String, _
            wsName As String, _
            cellRef As String _
                            ) As Variant
'// Modified From:
'// http://www.erlandsendata.no/english/index.php?d=envbawbreadfromclosedwb
    Dim arg As String
    GetInfoFromClosedFile = ""
    
    arg = "'" & wbPath & "[" & wbName & "]" & _
        wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
    On Error Resume Next
    GetInfoFromClosedFile = ExecuteExcel4Macro(arg)
End Function
Code:
Function CreateFileList( _
                    FileFilter As String, _
                    SearchFolder 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 = SearchFolder
        .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
 
Last edited:
Upvote 0
Yes this is it!:beerchug:
My only request, that after I add a separate sheet to run this macro, and output to my original report sheet (no problem there), but to make cell A1 content equal to the output of cell E24 on Sheet1 (ex). So when the value of E24 on Sheet1 changes (as a result of VLOOKUP), will run this macro. When I tried it, did not ran the macro. Sheet2 cell A1=(Sheet1!E24)
Used the macro on Sheet2.

:cool:
 
Upvote 0
The Change Event only triggers when a cell's content is changed so in the case of a formula the cell content stays =Sheet1!E24. To get an event to trigger when a cell value is changed by a formula you have to use the Calculate Event. The Calculate Event is a little tricky because it will trigger for a variety of reason not just when the cell value changes. The code has to keep track what was in the cell before the calculate event to prevent the macro from running every time the sheet is calculated.

The below code checks to see if A1 and A2 match if not it runs the macro and updates A2 to the new value. A2 being where the previous value is stored. You can change A2 to another cell if you don't want to see it or leave it there and hide it with formatting.

Replace the "Worksheet_Change" Sub with this one.
Code:
Private Sub Worksheet_Calculate()
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    If Range("A1").Value <> Range("A2").Value Then
            FilterXLS _
            Criteria:="*.xls", _
            SearchPath:="Z:\Seagate", _
            wsToCheck:="Sheet1", _
            CellToCheck:="C4", _
            ValueToMatch:=Range("A1").Value, _
            IncludeSubfolders:=True, _
            OutputCol:="B", _
            HyperlinkCol:="B"
        Range("A2").Value = Range("A1").Value
    End If
    Application.Calculation  = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub
 
Last edited:
Upvote 0
Works excellent in a test sheet.:)
My mistake that I forget, that the list is actually just the file name, so when I link the output to Sheet1, the path would not transfer and the link would not work.
Ex E9=HYPERLINK((Sheet2!B2)) on Sheet1.

Thank you.
 
Upvote 0
Thinking about this more all the code can be added to the same sheet. It will just be a matter of adjusting the ranges to suit. Make the following changes
Copy over the following to the sheet 1 code module
Sub FilterXLS
Function GetInfoFromClosedFile

Copy over the following to the sheet 1 code module and make changes to
Code:
Private Sub Worksheet_Calculate()
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    [U]'// Change Range("[COLOR="Red"]A2[/COLOR]") to suitable location to store the temp value[/U]
    If Range("E24").Value <> Range("[COLOR="red"][B]A2[/B][/COLOR]").Value Then
            FilterXLS _
            Criteria:="*.xls", _
            SearchPath:="Z:\Seagate", _
            wsToCheck:="Sheet1", _
            CellToCheck:="C4", _
            ValueToMatch:=Range("E24").Value, _
            IncludeSubfolders:=True, _
            [U]'// Change output columns to the desired[/U]
            OutputCol:="[B][COLOR="Red"]F[/COLOR][/B]", _
            HyperlinkCol:="[COLOR="red"][B]F[/B][/COLOR]"
        Range("[B][COLOR="Red"]A2[/COLOR][/B]").Value = Range("E24").Value
    End If
    Application.Calculation  = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub

I fairly certain that this should work but could you provide a description of the sheet layout, input and output locations.
 
Upvote 0

Forum statistics

Threads
1,224,531
Messages
6,179,380
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