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.
 
I am must be missing something or just tired. but could not get it to work.
This is the code I had originally on Sheet1.


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
    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 = 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



Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
    '
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value & "*.jpg", _
                    SearchPath:="Z:\Seagate", _
                    IncludeSubfolders:=True, _
                    OutputCol:="B", _
                    HyperlinkCol:="B"
        TestCreateFileListAndHyperlinks _
                    Criteria:=Range("A1").Value & "*.pdf", _
                    SearchPath:="C:\Folder2", _
                    IncludeSubfolders:=True, _
                    OutputCol:="C", _
                    HyperlinkCol:="C"
        TestCreateFileListAndHyperlinks _
                    Criteria:="*" & Range("A1").Value & "*.log", _
                    SearchPath:="C:\Folder3", _
                    IncludeSubfolders:=True, _
                    OutputCol:="D", _
                    HyperlinkCol:="D"
        TestCreateFileListAndHyperlinks _
                    Criteria:="*" & Range("B1").Value & "*.*", _
                    SearchPath:="C:\Folder4", _
                    IncludeSubfolders:=True, _
                    OutputCol:="E", _
                    HyperlinkCol:="E"
    End If
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
Copying over code in Sheet1, the following text turned red in the project:

Code:
Private Sub Worksheet_Calculate()
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    '// Change Range("A2") to suitable location to store the temp value
    If Range("E24").Value <> Range("A2").Value Then
           [COLOR=Red] FilterXLS _
            Criteria:="*.xls", _
            SearchPath:="Z:\Seagate", _
            wsToCheck:="Sheet1", _
            CellToCheck:="C4", _
            ValueToMatch:=Range("E24").Value, _
            IncludeSubfolders:=True, _
            '// Change output columns to the desired
            OutputCol:="F", _
            HyperlinkCol:="F"[/COLOR]
        Range("A2").Value = Range("E24").Value
    End If
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub
Also I tried the following, but had the same results:

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


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

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
The working sheet input is L30 (typing value) which triggers results in D27 and D29 , and the outputs I am targeting with thses codes is from L40 to S40.
 
Upvote 0

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
Remove this line from the red area "'// Change output columns to the desired" That's my mistake I added that line in post editor as a reminder to you and the line break _ is expecting the code to continue on that there.

Code:
        FilterXLS _
            Criteria:="*.xls", _
            SearchPath:="Z:\Seagate", _
            wsToCheck:="Sheet1", _
            CellToCheck:="C4", _
            ValueToMatch:=Range("E24").Value, _
            IncludeSubfolders:=True, _
            OutputCol:="F", _
            HyperlinkCol:="F"
 
Upvote 0
Rob,

Removed the line, but nothing happened entering any value in cell E4 Sheet1.
I may have an issue with the computer or excel. it looks up.
Hard drive is 4 years old, and even I would expect more life out of it, I had the unfortunate experience that they just go after 4 years.
Bottom line until I fix this issue, I cannot give you an accurate answer how it works.
Thanks for your patience.
 
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