Posted by: garbagegigo October 17, 2009
excel help
Login in to Rate this Post:     0       ?        
Here you go. This VBA function is a function that I use in one of my VBA programs. All I had to do was modify it slightly for your purposes. All you have to do is simply call the function like:
searchFile "*.txt", "c:\", False

Hope this helps



'Returns 1 on success           0 on Failure
'You can use wildcards also in the filename.
'   Ex: *.txt
'
'Note:     Don't do: searchFile "*.txt", "c:\", True  (Your computer might hang)
Function searchFile(file_name As String, path_to_search As String, look_in_sub_folders As Boolean)
    Dim perr, res_row_no, res_row_col
    Dim File_Path As String, out_file As String, title1 As String, add_extension As String, res_sheet_name As String
    Dim No_Of_Files As Integer, i As Integer
    
    On Error GoTo Err_searchFile
    title1 = "File Search v1.0"
    
    '**********************************************
    'You can modify these values
    '**********************************************
    res_sheet_name = "Sheet3"       'If you are in a different sheet, simply put the sheet name here
    res_row_no = 1  'Give the starting row number where you want the results displayed
    res_row_col = "a"   'Give the column where you want the results to be displayed
    '**********************************************
    '**********************************************

    'Don't modify
    res_row_col = Asc(UCase(res_row_col)) - 65 + 1

    'Search for the file
    With Application.FileSearch
        .NewSearch
        .LookIn = path_to_search
        .filename = file_name
        .SearchSubFolders = look_in_sub_folders
        .Execute
    
        No_Of_Files = .FoundFiles.Count
        If No_Of_Files <= 0 Then
            MsgBox "Sorry couldn't find " & file_name & " in " & path_to_search & ".", , title1
            GoTo failed_exit
        Else    'If the file(s) was found
            For i = 1 To No_Of_Files
               Worksheets(res_sheet_name).Cells(i + res_row_no - 1, res_row_col).Value = .FoundFiles(i)
            Next i
        End If
    End With
    searchFile = 1      'Success code
    Exit Function       'Sucessful exit of the function

Err_searchFile:
    perr = Err
    MsgBox "ERROR! Inside searchFile. " & Err.Description, , title1

failed_exit:
    searchFile = 0
End Function

Read Full Discussion Thread for this article