-3

I have a code which can transfer the Excel files from one folder to another but i would like to update the code so that it can move all the files (.xml, .txt, .pdf, etc.) from one folder to another.

Sub MoveFiles()
    
    Dim sourceFolderPath As String, destinationFolderPath As String
    Dim FSO As Object, sourceFolder As Object, file As Object
    Dim fileName As String, sourceFilePath As String, destinationFilePath As String
    
    Application.ScreenUpdating = False
    
    sourceFolderPath = "E:\Source"
    destinationFolderPath = "E:\Destination"
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set sourceFolder = FSO.GetFolder(sourceFolderPath)
    
    For Each file In sourceFolder.Files
    
        fileName = file.Name
    
        If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved
    
            sourceFilePath = file.Path
            destinationFilePath = destinationFolderPath & "\" & 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 = Nothing    
    Set FSO = Nothing    
End Sub


can you please help
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
Salman
  • 33
  • 8
  • 7
    Do you understand what `If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved` does? – BigBen Jul 29 '22 at 12:58
  • 5
    Just a remark: Despite common believe, the 2 last statement (setting the objects to Nothing) are superfluous. – FunThomas Jul 29 '22 at 13:10
  • It is, btw, common sense that you, when copying code, give credits to the author. I fixed that for you: https://stackoverflow.com/a/46715073/7599798 – FunThomas Jul 29 '22 at 16:21
  • 1
    `Setting objects = Nothing` explained by [the legend himself here](https://stackoverflow.com/questions/51065566/what-are-the-benefits-of-setting-objects-to-nothing) – urdearboy Jul 29 '22 at 17:07
  • Dear Sir,I am a marketing guy, however i have started taking interest in VBA and automation which is very powerful. Thanks for correcting me – Salman Jul 31 '22 at 14:17

1 Answers1

1

Move Files Using MoveFile

  • You would get greater control of things by using CopyFile and DeleteFile instead of MoveFile.
  • Using Dir, FileCopy, and Kill, instead of the FileSystemObject object and its methods, would make it simpler and also faster.
Option Explicit

Sub MoveFilesTEST()

    Const sFolderPath As String = "E:\Source"
    Const dFolderPath As String = "E:\Destination"
    Const FilePattern As String = "*.*"
    
    MoveFiles sFolderPath, dFolderPath, FilePattern

End Sub

Sub MoveFiles( _
        ByVal SourceFolderPath As String, _
        ByVal DestinationFolderPath As String, _
        Optional ByVal FilePattern As String = "*.*")
    
    Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
    
    If Not fso.FolderExists(SourceFolderPath) Then
        MsgBox "The source folder path '" & SourceFolderPath _
            & "' doesn't exist.", vbCritical
        Exit Sub
    End If
    
    If Not fso.FolderExists(DestinationFolderPath) Then
        MsgBox "The destination folder path '" & DestinationFolderPath _
            & "' doesn't exist.", vbCritical
        Exit Sub
    End If
    
    Dim apSep As String: apSep = Application.PathSeparator
    
    Dim sPath As String: sPath = SourceFolderPath
    If Left(sPath, 1) <> apSep Then sPath = sPath & apSep
        
    Dim sFolder As Object: Set sFolder = fso.GetFolder(sPath)
    If sFolder.Files.Count = 0 Then
        MsgBox "There are no files in the source folder '" & sPath & "'.", _
            vbExclamation
        Exit Sub
    End If
    
    Dim dPath As String: dPath = DestinationFolderPath
    If Left(dPath, 1) <> apSep Then dPath = dPath & apSep
        
    Dim dFolder As Object: Set dFolder = fso.GetFolder(dPath)
    
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    
    Dim sFile As Object
    Dim dFilePath As String
    Dim ErrNum As Long
    Dim MovedCount As Long
    Dim NotMovedCount As Long
    
    For Each sFile In sFolder.Files
        dFilePath = dPath & sFile.Name
        If fso.FileExists(dFilePath) Then
            dict(sFile.Path) = Empty
            NotMovedCount = NotMovedCount + 1
        Else
            On Error Resume Next
                fso.MoveFile sFile.Path, dFilePath
                ErrNum = Err.Number
                ' e.g. 'Run-time error '70': Permission denied' e.g.
                ' when the file is open in Excel
            On Error GoTo 0
            If ErrNum = 0 Then
                MovedCount = MovedCount + 1
            Else
                dict(sFile.Path) = Empty
                NotMovedCount = NotMovedCount + 1
            End If
        End If
    Next sFile
    
    Dim Msg As String
    Msg = "Files moved: " & MovedCount & "(" & NotMovedCount + MovedCount & ")"
    If NotMovedCount > 0 Then
        Msg = Msg & vbLf & "Files not moved:" & NotMovedCount & "(" _
            & NotMovedCount + MovedCount & ")" & vbLf & vbLf _
            & "The following files were not moved:" & vbLf _
            & Join(dict.keys, vbLf)
    End If
    
    MsgBox Msg, IIf(NotMovedCount = 0, vbInformation, vbCritical)
 
End Sub
VBasic2008
  • 44,888
  • 5
  • 17
  • 28
  • Thanks everyone for helping me in creating the macros i needed espeically VBasic2008 – Salman Aug 07 '22 at 10:02
  • with your help currently i am able to first copy specific files (names mentioned in excel sheet) into multiple folders by using partial lists and then i have inserted another code provided by you and through which i can now move the files from source folder into another Archive folder. – Salman Aug 07 '22 at 10:04
  • I am doing this by inserting 2 modules, in the first macro i am able to copy files and second to move files into archive and in order to run both macros simultaneously i have added another macro which runs these both macros one after another automatically. – Salman Aug 07 '22 at 10:06
  • i request for one more help, is there anyway through which i can run all 3 macros after every 15 minutes? i mean for now i need to press the button after every 15 minutes, can i automate this ? – Salman Aug 07 '22 at 10:09
  • Look into the [Application.OnTime method](https://learn.microsoft.com/en-us/office/vba/api/excel.application.ontime) and experiment with it. If you run into trouble, ask another question. I'm not too familiar with it. – VBasic2008 Aug 07 '22 at 12:15
  • Thanks, i will check and will let you know. – Salman Aug 10 '22 at 12:09
  • Dear VB i have pasted the code in Visual basic pane as Module4 Application.OnTime Now + TimeValue("00:00:15"), "Sub Button1_Click()" but this does not work. – Salman Aug 10 '22 at 12:39
  • Sub Button1_Click() is the third module which is basically to run first 2 modules automatically i.e. to copy the files into sub folders and then to move those files from source folder to another folder. can you please help – Salman Aug 10 '22 at 12:39