EXCEL VBA 将文件从不同的路径移动到不同的路径

EXCEL VBA move files from different paths to different path

我有一个 excel vba 代码运行良好,如下所示,但我希望它将文件从不同路径移动到不同路径。我可以循环吗?

示例:

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

来自上面的评论:

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