Home » excel » excel – Search for a file and return path

excel – Search for a file and return path

Posted by: admin May 14, 2020 Leave a comment


I need some ideas here… I have a column which has file names. I have a folder which has all the excel files. Is it possible to link both these and get the file path in adjacent cell?

for example: I have a value “AAA”, “BBB”,and so on in column A1,A2 similarly I have a set of excel files in a folder with name AAA.xlsx, BBB.xlsx.

Ill choose folder path to macro manually everytime.

Finally, by comparing the cell value in column A and file name in the folder, the file path should be displayed in column B for matched items.

How to&Answers:

Following your last edit this should work:

Sub SetFullPath()

MyPath = "C:\Insert path of the folder where you have the files here\"
For Each cell In Range("B1:B100")'Customize your range
If Len(Dir(MyPath & Range("A" & cell.Row).Value & ".xlsx")) = 0 Then
cell.Value = "File Not Found"
Else: cell.Value = MyPath & Range("A" & cell.Row).Value & ".xlsx"
End If

End Sub

Let me know if something has to be changed.


This sub (return_paths) should do it. It uses the function GivePath.

Sub return_paths()
  Dim sSearchPath As String: sSearchPath = "C:\Temp"
  Dim oFSO As Object
  Dim i As Long
  Set oFSO = CreateObject("Scripting.FileSystemObject")
  For i = 1 To ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
    ActiveSheet.Cells(i, 2) = GivePath(ActiveSheet.Cells(i, 1), oFSO.GetFolder(sSearchPath))
End Sub

Private Function GivePath(sName As String, oDir As Object, Optional ByRef blnFound As Boolean) As String
  Dim f As Object
  Dim sf As Object

  If blnFound Then Exit Function

  For Each f In oDir.Files
    If f.Name = sName Then
      GivePath = f.Path
      blnFound = True
    End If
    If blnFound Then Exit Function

  For Each sf In oDir.SubFolders
    GivePath = GivePath(sName, sf, blnFound)
    If blnFound Then Exit Function

  If GivePath = "" Then GivePath = "The file was not found"

End Function

After running the result looks like this:
results after the search


Please find the solution I got from consolidating all results. Thanks guys. you all are awesome!!!

Sub FolderDetails()
Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim rRng As Range, rCl As Range
Dim sFolder As String
''// Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1)
End If
End With
Set rRng = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp))
For Each rCl In rRng
If FSO.FileExists(sFolder & Application.PathSeparator & rCl.Value & ".xlsx") Then
rCl.Offset(, 1).Value = sFolder
Else: rCl.Offset(, 1).Value = "The File Does Not Exist"
End If
Next rCl
End Sub