Forum Discussion
Ozz_Kozz
Sep 30, 2020Copper Contributor
Matching file names in Excel column to file names in folder
Hi, I have a column in excel that contains the file names of files that are in a folder (ex: IMG_001, contacs.pdf, essay.docx). I have about 30 rows with miscellaneous file names in the column, and ...
Subodh_Tiwari_sktneer
Oct 03, 2020Silver Contributor
Okay, please try the following code and see if this is something you can work with.
The following code will check the files listed in column 4 of the Table on Sheet called "B" in the Document folder and if it finds the file in that folder, it will highlight the cell with filename in the Table and copy the file from Document folder to a Sub-Folder called "Found Files".
Sub SearchFiles()
Dim ws As Worksheet
Dim tbl As ListObject
Dim cel As Range
Dim rootFolder As String
Dim strNameNewSubFolder As String
Dim fso As FileSystemObject
Dim newFolder As Folder
Dim fil As File
Dim strFilepath As String
Dim newFilePath As String
Set fso = New FileSystemObject
Set ws = Worksheets("B")
Set tbl = ws.ListObjects(1)
'Path of the Source folder with files
rootFolder = "C:\Users\sktneer\Documents"
If Not fso.FolderExists(rootFolder) Then
MsgBox rootFolder & " doesn't exist.", vbExclamation, "Source Folder Not Found!"
Exit Sub
End If
'files that are found in the Source Folder would be copied to this New Sub-Folder
'Change the name of the Sub-Folder as per your requirement
strNameNewSubFolder = "Found Files"
If Right(rootFolder, 1) <> "/" Then rootFolder = rootFolder & "/"
If Not fso.FolderExists(rootFolder & strNameNewSubFolder) Then
fso.CreateFolder rootFolder & strNameNewSubFolder
End If
Set newFolder = fso.GetFolder(rootFolder & strNameNewSubFolder)
tbl.DataBodyRange.Columns(4).Interior.ColorIndex = xlNone
For Each cel In tbl.DataBodyRange.Columns(4).Cells
strFilepath = rootFolder & cel.Value
newFilePath = newFolder.Path & "/" & cel.Value
If fso.FileExists(strFilepath) Then
cel.Interior.Color = vbYellow
Set fil = fso.GetFile(strFilepath)
'The following line will copy the file found to the newly created Sub-Folder
fil.Copy newFilePath
End If
Next cel
Set fso = Nothing
End SubSubodh_Tiwari_sktneer
Oct 03, 2020Silver Contributor
Just forgot to tell you that you will need to add a reference to a library called "Microsoft Scripting Runtime".
To do so, go to Tools on VB Editor's Ribbon --> References --> search for the library called "Microsoft Scripting Runtime" and check the CheckBox next to it and click OK to finish.