'EXCEL VBA move files from different paths to different path
I have an excel vba code that works very well as seen below, but I want it to move files from different paths to different paths. Can I loop for this?
Example:
sourceFolderPath = "C:\Users\test1" destinationFolderPath = "C:\Users\test2"
sourceFolderPath = "C:\Users\tes3" destinationFolderPath = "C:\Users\test4"
sourceFolderPath = "C:\Users\test5" destinationFolderPath = "C:\Users\test6"
Sub MoveFiles()
Dim sourceFolderPath As String, destinationFolderPath As StringDim FSO As Object, sourceFolder As Object, file As ObjectDim fileName As String, sourceFilePath As String, destinationFilePath As StringDim strTime As String
strTime = Format(Now, "yyyymmddhhmm")
Application.ScreenUpdating = False
sourceFolderPath = "C:\Users\test"
destinationFolderPath = "C:\Users\test2"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.Getfolder(sourceFolderPath)
For Each file In sourceFolder.Files
fileName = file.Name
If InStr(fileName, ".xlsx") Or InStr(fileName, ".xls") Then ' Only xlsx files will be moved
sourceFilePath = file.Path
destinationFilePath = destinationFolderPath & "" & strTime & fileName
FSO.movefile Source:=sourceFilePath, Destination:=destinationFilePath
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be moved
Next
'Don't need set file to nothing because it is initialized in for each loop
'and after this loop is automatically set to Nothing
Set sourceFolder = NothingSet FSO = Nothing
End Sub
Solution 1:[1]
From comment above:
Sub Tester()
MoveFiles "C:\Temp\SO\", "C:\Temp\SO2\"
MoveFiles "C:\Users\test3\", "C:\Users\test4\"
End Sub
Sub MoveFiles(sourceFolderPath As String, destinationFolderPath As String)
Dim file As Object, fileName As String, strTime As String
strTime = Format(Now, "yyyymmddhhmm")
For Each file In CreateObject("Scripting.FileSystemObject"). _
Getfolder(sourceFolderPath).Files
fileName = file.Name
If fileName Like "*.xlsx" Or fileName Like "*.xls" Then
file.Move destinationFolderPath & "" & strTime & fileName
End If
Next
'really no need to set objects to Nothing when done...
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Williams |
