I have a set of excel files named apple.xlsx, mango.xlsx etc. These all are in "C:\Users\Public\Fruits\". I stored all fruits name in fruits.xlsx. I am a newbie in Excel-VBA. May I know how to move these files to folders Apple, Mango upto 500 folders for 500 different fruits ?
1 Answer
You can use the Name Statement to change the name and location of files.
For example:
Name "C:\Example_Folder_1\apple.xlsx" As "C:\Example_Folder_2\apple.xlsx"
This will move the file to Example_Folder_2 from Example_Folder_1.
You can combine this with a loop if you already have the names of all your files. For example, if the list of fruits were in the range A2:A500 like this:
| A
1|Fruits
2|Apple
3|Mango
4|Pear
5|Banana
You could do this:
Sub MoveFiles()
Dim flName as String, OldFldr as String, NewFldr as String
Dim Cell as Range
'Set old folder name
OldFldr = "C:\Users\Public\Fruits\"
'Loop through fruits
For each Cell in Thisworkbook.Sheets("Fruits").Range("A2:A500")
'Set new folder name
NewFldr = OldFldr & Cell.Value
'Check whether new fruit specific folder already exists and if not, create it
If Dir(NewFldr , vbDirectory) = "" Then
MkDir (NewFldr & "\")
End If
'Set filename
flName = Cell.Value & ".xlsx"
'Move file to new folder
Name Oldfldr & flName As NewFldr & "\" & flName
Next Cell
End Sub
This will put your fruit specific files into fruit specific folders.