Search and move files to another folder with VBA - excel

Maybe someone can help me.
I am looking for a vba code thats searches in a folder for kewords of the filename, and then moves these found files to anthor folder.
The keywords are stored in column A in excel.
I have used the following code and it works partly. The problem is that column A has to contain the exact filename in the following code. I want vba to search for keywords. The other thing is that the files have to be moved instead of been copied. And if a file has been moved that there is check in column B.
Sub Test()
Dim R As Range, r1 As Range
Dim SourcePath As String, DestPath As String, FName As String
SourcePath = "C:\Downloads\"
DestPath = "C:\Downloads\New folder\"
Set r1 = Range("A1", Range("A" & Rows.Count).End(xlUp))
For Each R In r1
FName = Dir(SourcePath & R)
Do While FName <> ""
If Application.CountIf(r1, FName) Then
FileCopy SourcePath & FName, DestPath & FName
R.Offset(0, 1).Value = FName
Else
MsgBox "Bad file: " & FName & " ==>" & FName & "<== "
End If
FName = Dir()
Loop
Next
End Sub

You can use wildcards in the Dir function if your range only contains keywords of the file. Like this:
FName = Dir(SourcePath & "*" & R.Value & "*")
It will then process all files where this keyword is used in.

Related

To change the folder path in VBA code to execute

I am working on a code which Moves the files after matching the file name into the folders accordingly "moveMatchedFilesInAppropriateFolders"
In order to run this code it is required that the Excel sheet should be saved in the same folder where the files and folders are available e.g. Folders and Files are saved in Drive E:\Archive. Therefore it is also important that the excel sheet should also be saved in the same folder (E:\Archive.
However i do not want to save the excel sheet in the same folder where the files and folders are placed and i wanted to save the excel sheet in some other Drive (e.g. Drive G). Is there any possibility where if i saved this excel sheet in other Drive and just give the path to it the code should run and not give error.
Sub moveMatchedFilesInAppropriateFolders()
Dim sh As Worksheet, lastR As Long, filesPath As String, fileName As String, foldersRoot As String, FolderPath As String
Dim arr, boolNotFound As Boolean, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
arr = sh.Range("A2:A" & lastR).Value2
foldersRoot = ThisWorkbook.Path & "\" 'use here the root folder for folders
filesPath = "G:\!Archive Management\2023\" 'use here the path where the files can be found
Set FSO = CreateObject("Scripting.FileSystemObject") 'to check if file exists
For i = 1 To UBound(arr)
boolNotFound = False
If Dir(foldersRoot & arr(i, 1), vbDirectory) <> "" Then
FolderPath = foldersRoot & arr(i, 1) & "\"
Else
MsgBox arr(i, 1) & " folder could not be found!" & vbCrLf & _
"Please, note and correct it after copying the matching ones and run the code again!"
boolNotFound = True
End If
If Not boolNotFound Then
fileName = Dir(filesPath & arr(i, 1) & "*.*")
Do While fileName <> ""
If Not FSO.FileExists(FolderPath & fileName) Then 'move/copy only if it does not exist in destination fld
'uncomment the way you need (moving or copying):
Name filesPath & fileName As FolderPath & fileName 'the file is moved
'FileCopy filesPath & fileName, folderPath & fileName 'the file is copied
End If
fileName = Dir
Loop
End If
Next i
End Sub

How to copy files with similar name into folders?

I am creating an archiving system where I need to sort files into folders.
I create the folders automatically by mentioning the names of folder in an Excel sheet.
Now I need to copy the files with similar names in that respective folder.
E.g. A folder is created with the name "Ashley Davidson". All the files which are in one source folder and whose file name starts with Ashley Davidson should be copied to this folder.
There will be more than 500 folders and more than 10,000 files to be copied in these folders every week.
The code below creates the folders.
How can I copy the files based on similar name to these folders?
Important
The names of folders will be constant.
The start of the names of files will be similar but users add other words like date, age, sheet 1, sheet 2 etc., therefore List of Partial name concept will probably work here.
Examples of folder names
Example of file names
Code to create folders:
Sub MakeFolders()
Dim sh As Worksheet, lastR As Long, arr, i As Long, rootPath As String
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
arr = sh.Range("A2:A" & lastR).Value2
rootPath = ThisWorkbook.Path & "\"
For i = 1 To UBound(arr)
If arr(i, 1) <> "" And noIllegalChars(CStr(arr(i, 1))) Then
If Dir(rootPath & arr(i, 1), vbDirectory) = "" Then
MkDir rootPath & arr(i, 1)
End If
Else
MsgBox "Illegals characters or empty cell (" & sh.Range("A" & i + 1).Address & ")..."
End If
Next i
End Sub
Function noIllegalChars(x As String) As Boolean
Const illCh As String = "*[\/\\"":\*?]*"
If Not x Like illCh Then noIllegalChars = True
End Function
You did not answer the clarification question and I need to leave my office. The next code assumes that all files exist in a common folder and they should be moved in the folder exactly named as the string in column A:A of the active sheet. It is able to move or copy the file, according to the line you should uncomment:
Sub moveMatchedFilesInAppropriateFolders()
Dim sh As Worksheet, lastR As Long, filesPath As String, fileName As String, foldersRoot As String, folderPath As String
Dim arr, boolNotFound As Boolean, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
arr = sh.Range("A2:A" & lastR).Value2
foldersRoot = ThisWorkbook.Path & "\" 'use here the root folder for folders
filesPath = "your files to be processed folder" 'use here the path where the files can be found
Set fso = CreateObject("Scripting.FileSystemObject") 'to check if file exists
For i = 1 To UBound(arr)
boolNotFound = False
If Dir(foldersRoot & arr(i, 1), vbDirectory) <> "" Then
folderPath = foldersRoot & arr(i, 1) & "\"
Else
MsgBox arr(i, 1) & " folder could not be found!" & vbCrLf & _
"Please, note and correct it after copying the matching ones and run the code again!"
boolNotFound = True
End If
If Not boolNotFound Then
fileName = Dir(filesPath & arr(i, 1) & "*.*")
Do While fileName <> ""
If Not fso.FileExists(folderPath & fileName) Then 'move/copy only if it does not exist in destination fld
'uncomment the way you need (moving or copying):
'Name filesPath & fileName As folderPath & fileName 'the file is moved
'FileCopy filesPath & fileName, folderPath & fileName 'the file is copied
End If
fileName = Dir
Loop
End If
Next i
End Sub
Not tested, but it should work.
If you need something else, please better answer my last clarifications question.
Besides all that, I think it would be good to place a marker in B:B column, for not found folders, if any. In this way, the code can be adapted that at the next run to only run the ones having the marker (and delete it, if the string has been corrected and the folder has been found).
My code works from having the new Folders in the same folder as the workbook you've created said folders from (as it is in your code) and the files to be copied were in a seperate folder in the same path as your workbook; I found that easier to work with since then the only files in that folder are files to be copied, not extra folders within.
Sub copyFilesToFolder()
Dim lRow As Long
Dim wb As Workbook
Dim ws As Worksheet
Dim ccell As Range
Dim fsO As Object, oFolder As Object, oFile As Object
Dim pathFiles As String, sFolderPath As String, sSource As String, sDestination As String
Set wb = ActiveWorkbook
Set ws = wb.ActiveWorksheet
lRow = Range("A" & Rows.Count).End(xlUp).Row
pathFiles = "Q:\WHERE YOUR ORIGINAL WORKBOOK IS\Test\" 'could be gotten from wb technically
Set fsO = CreateObject("Scripting.FileSystemObject")
Set oFolder = fsO.GetFolder(pathFiles)
For Each oFile In oFolder.Files 'go through all the files
For Each ccell In Range("A2:A" & lRow).Cells 'go through all the folder-names
'Debug.Print ccell.Value2
'Debug.Print oFile.Name
If InStr(oFile.Name, ccell.Value2) > 0 Then 'if folder name is in file name
sFolderPath = wb.Path & "\" & ccell.Value2 & "\"
If Dir(sFolderPath, vbDirectory) <> "" Then 'if Folder exists
sDestination = sFolderPath & oFile.Name
If Dir(sDestination) = "" Then 'file doesn't exist yet
sSource = pathFiles & oFile.Name
'Debug.Print sSource
'Debug.Print sDestination
Call fsO.CopyFile(pathFiles & oFile.Name, sFolderPath & oFile.Name)
GoTo Skip
End If
Else
MsgBox ("Folder " & ccell.Value2 & " doesn't exist yet")
End If
End If
Next ccell
Skip:
Next oFile
End Sub
Hope this helps :)

copy file from excel list with extension to other folder

I am new in VBA, so I have a list of document (with extension .pdf, .docx, etc) in excel column. What I would like to do is to copy all document in the list, from source folder to destination folder.
I already tried some code, it works but the code copy all the files in the folder instead of the file in list (The document list is only in B3:B10).
Any help really appreciated.
Thanks in advance.
Sub copyfile()
Dim r As Range
Dim Jajal As Range
Dim sourcePath As String, DestPath As String, FName As String
sourcePath = "C:\Users\"
DestPath = "H:\Users\"
For Each r In Range(Sheet6.Range("B3"), Sheet6.Range("B10")) 'the list document is in the sheet6 B3:B10
FName = Dir(sourcePath & r)
'Loop while files found
Do While FName <> ""
'Copy the file
FileCopy sourcePath & FName, DestPath & FName
'Search the next file
FName = Dir()
Loop
Next
End Sub
Copy Files From Range (List)
The Code
Option Explicit
' This will copy files found in a source path AND whose names
' are contained in a list (range), to a destination path,
' overwriting possible existing files.
Sub copyFiles()
Const SourcePath As String = "C:\Users\"
Const DestPath As String = "H:\Users\"
Const ListAddress As String = "B3:B10"
' Write file list to array.
Dim FileList As Variant: FileList = Sheet1.Range(ListAddress).Value
' 'Get' first file name.
Dim FName As String: FName = Dir(SourcePath)
' 'Initiate' counter.
Dim i As Long
' Loop files in SourcePath.
Do While FName <> ""
' Check if file name of current file is contained in array (FileList).
If Not IsError(Application.Match(FName, FileList, 0)) Then
' Count file.
i = i + 1
' Copy file.
FileCopy SourcePath & FName, DestPath & FName
End If
' 'Get' next file name.
FName = Dir()
Loop
' Inform user.
Select Case i
Case 0: MsgBox "No files found", vbExclamation, "No Files"
Case 1: MsgBox "Copied 1 file.", vbInformation, "Success"
Case Else: MsgBox "Copied " & i & " files.", vbInformation, "Success"
End Select
End Sub
Using Dir you loop over all the files in the directory. If you know your files, you don't need Dir. Try like the following (not tested):
Sub copyfile()
Dim r As Range
Dim Jajal As Range
Dim sourcePath As String, DestPath As String
sourcePath = "C:\Users\"
DestPath = "H:\Users\"
For Each r In Range(Sheet6.Range("B3"), Sheet6.Range("B10")) 'the list document is in the sheet6 B3:B10
'Loop while files found
If r.Value <> ""
'Copy the file
FileCopy sourcePath & r.Value, DestPath & r.Value
'Search the next file
End If
Next
End Sub
However, you could test if the file exists before you copy.

copy file from excel listto other folder

I am new in VBA, so I have a list of document (just file name, without extension .pdf, .docx, etc) in excel column. What I would like to do is to copy all document in the list, from source folder to destination folder.
I already tried some code, it works but the code copy all the files in the folder instead of the file in list (The document list is only in B3:B10).
Any help really appreciated.
Thanks in advance.
Sub copyfile()
Dim r As Range
Dim Jajal As Range
Dim sourcePath As String, DestPath As String, FName As String
sourcePath = "C:\Users\"
DestPath = "H:\Users\"
For Each r In Range(Sheet6.Range("B3"), Sheet6.Range("B10")) 'the list document is in the sheet6 B3:B10
FName = Dir(sourcePath & r)
'Loop while files found
Do While FName <> ""
'Copy the file
FileCopy sourcePath & FName, DestPath & FName
'Search the next file
FName = Dir()
Loop
Next
End Sub
You shouldn't need the Dir method
For Each r In Range(Sheet6.Range("B3"), Sheet6.Range("B10")) 'the list document is in the sheet6 B3:B10
FileCopy sourcePath & r.value, DestPath & r.value
Next

Excel VBA Search in folder and subfolders and returns multiple files

I have to search and copy a number of files in a folder starting from an Excel list like:
8100 ' cell "A2"
8152 ' cell "A3"
8153 ' cell "A4"
in the source folders there are files named like this:
8153.pdf
100_8152.pdf
102_8153.pdf
8153 (2).pdf
How can I find these files and copy ALL the files that matches in a separate folder? The code returns only one file, but I need ALL the files matching the cell value. I need to extend my research in subfolders organized by years too (ie: "D:\myfolder\2015", "D:\myfolder\2016", etc.).
Thanks to user3598756, I'm now using this code:
Option Explicit
Sub cerca()
Dim T As Variant
Dim D As Variant
T = VBA.Format(VBA.Time, "hh.mm.ss")
D = VBA.Format(VBA.Date, "yyyy.MM.dd")
Dim Source As String
Dim Dest As String
Dim Missed As String
Dim fileFound As String
Dim CodiceCS As Variant
Dim cell As Range
Source = "D:\myfolder\"
Dest = "D:\myfolder\research " & D & " " & T
If Dir(Dest, vbDirectory) = "" Then MkDir Dest '<--| create destination folder if not alerady there
With Worksheets("Cerca") '<-- reference your worksheet with pdf names
For Each cell In .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- loop through its column "A" cells with "constant" (i.e. not resulting from formulas) values from row 2 down to last non empty one
CodiceCS = VBA.Left((cell.Value), 4)
fileFound = Dir(Source & "\" & CodiceCS & "\*" & cell.Value & "*.Pdf") '<-- look for a source folder file whose name contains the current cell value
If fileFound <> "" Then '<-- if found...
FileCopy Source & "\" & CodiceCS & "\" & fileFound, Dest & "\" & fileFound '<-- ...copy to destination folder
Else '<--otherwise...
Missed = Missed & cell.Value & vbCrLf '<--... update missing files list
End If
Next cell
End With
If Missed <> "" Then '<-- if there's any missing file
Dim FF As Long
FF = FreeFile
Open (Dest & "\" & "MissingFiles.txt") For Output As #FF
Write #FF, VBA.Left(Missed, Len(Missed) - 2)
Close #FF
End If
MsgBox "OK"
Shell "explorer.exe " + Dest, vbNormalFocus
End Sub
This code will place all the file names in the main folder and subfolders into an array. It then looks through the array for matching values.
I've included an extra couple of lines which I've commented out - these are different options you could do within the code.
Public Sub cerca()
Dim DT As String
Dim Source As String
Dim Dest As String
Dim vFiles As Variant
Dim vFile As Variant
Dim rCell As Range
Dim oFSO As Object
Dim FileFound As Boolean
Dim FF As Long
FF = FreeFile
DT = Format(Now, "yyyy.mm.dd hh.mm.ss")
Set oFSO = CreateObject("Scripting.FileSystemObject")
Source = "D:\myfolder\"
Dest = "D:\myfolder\research " & DT
If Dir(Dest, vbDirectory) = "" Then MkDir Dest
'Get the full path name of all PDF files in the source folder and subfolders.
vFiles = EnumerateFiles(Source, "pdf")
With Worksheets("Cerca")
'Look at each cell containing file names.
For Each rCell In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
FileFound = False 'Assume the file hasn't been found.
'Check each value in the array of files.
For Each vFile In vFiles
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Use this line if the file name in the sheet exactly match the file name in the array. '
'8152 and 100_8152.pdf are not a match, 8152 and 8152.pdf are a match. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rCell & ".pdf" = FileNameOnly(vFile) Then
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Use this line if the file name in the sheet should appear in the file name in the array. '
'8152 and 100_8152.pdf are a match, 1852 and 8152.pdf are a match. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If InStr(FileNameOnly(vFile), rCell.Value) > 0 Then
'If found copy the file over and indicate it was found.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This line will use the rcell value to name the file. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
oFSO.CopyFile vFile, Dest & "\" & rCell & ".pdf"
''''''''''''''''''''''''''''''''''''''
'This line will not rename the file. '
''''''''''''''''''''''''''''''''''''''
'oFSO.CopyFile vFile, Dest & "\" & FileNameOnly(vFile)
FileFound = True
End If
Next vFile
'Any file names that aren't found are appended to the text file.
If Not FileFound Then
Open (Dest & "\" & "MissingFiles.txt") For Append As #FF ' creates the file if it doesn't exist
Print #FF, rCell ' write information at the end of the text file
Close #FF
End If
Next rCell
End With
End Sub
Public Function EnumerateFiles(sDirectory As String, _
Optional sFileSpec As String = "*", _
Optional InclSubFolders As Boolean = True) As Variant
EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")
End Function
Public Function FileNameOnly(ByVal FileNameAndPath As String) As String
FileNameOnly = Mid(FileNameAndPath, InStrRev(FileNameAndPath, "\") + 1, Len(FileNameAndPath))
End Function

Resources