How to Use Excel VBA to Move Files

A File System Object (FSO) is an object in VBA that provides a way to work with files and folders on a computer’s file system. It allows VBA code to create, read, modify and delete files and folders, as well as perform other file system operations, such as copying, moving and renaming files and folders.

To move files using Excel VBA, we need to ensure that the Microsoft Scripting Runtime box is checked. To do this, go to Tools and click on References.

Open VBA Reference Library

Search Microsoft Scripting Runtime and check the box beside it.

Check the box of Microsoft Scripting Runtime to move files using Excel VBA


MoveFile Method Syntax

object.MoveFile source, destination
Part Required/Optional Description
Object Required The name of a File System Object
Source Required The path of the files to be moved
Destination Required The path where the files are to be moved

How to Launch VBA Editor in Excel

To access the Microsoft Visual Basic window, go to the Developer tab and click on Visual Basic. You can also open it by pressing Alt+F11 on your keyboard.

Go to Microsoft Visual Basic Application

Go to the Insert tab and click on Module to open the code Module.

Insert a code Module in VBA


How to Move a Single File from One Folder to Another Using Excel VBA

We will move a file named UDF.xlsx which is located in “D:\Source Folder\” path. We will move it to “D:\Destination Folder\User Defined Function\”.

  • Open the Microsoft VBA code Module.
  • Enter the following code in it.
Sub MoveSingleFile()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.MoveFile "D:\Source Folder\UDF.xlsx", _
    "D:\Destination Folder\User Defined Function\UDF.xlsx"
End Sub

code to Move a single file

Code Breakdown

fso.MoveFile "D:\Source Folder\UDF.xlsx", _
    "D:\Destination Folder\User Defined Function\UDF.xlsx"
  • This part moves a file named xlsx from the Source Folder directory located at “D:” to a subfolder named “User Defined Function” within the “Destination Folder” directory.
  • Press F5 or the Run button to run the code.
  • The file will be moved to the destination folder.

Move a single file using Excel VBA code


Excel VBA to Move Files: 5 Suitable Examples

We will move files from the source folder (D:\Source Folder) that contains six files.

Move files in Excel


Example 1 – Move Multiple Files from One Folder to Another

We will move multiple files from one folder to another using FileSystemObject.


1.1 Move Multiple Files with Same Extensions

  • Enter the following code in the VBA code Module.
Sub MoveFilewithSameExtensions()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.MoveFile "D:\Source Folder\*.xlsx", _
    "D:\Destination Folder\User Defined Function\"
End Sub

Code to Move files with same extensions

Code Breakdown

 fso.MoveFile "D:\Source Folder\*.xlsx", _
 "D:\Destination Folder\User Defined Function\"
  • This part moves the files that contain “.xlsx” in their name from “D:\Source Folder” to “D:\Destination Folder\User Defined Function\” location.
  • Run the code and you will find that all the files with the “.xlsx” extension are moved to the destination folder.

Moved files with same extensions

Note: You can change the source folder and destination folder as required.

Read More: Excel VBA: Delete Files with Wildcards


1.2 Move All Files from a Folder

  • Insert the VBA code given below in the Module.
Sub MoveAllFiles()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.MoveFile "D:\Source Folder\*", _
    "D:\Destination Folder\All\"
End Sub

Code to Move all files of a folder

Code Breakdown

fso.MoveFile "D:\Source Folder\*", _
"D:\Destination Folder\All\"
  • This code moves all the files from “D:\Source Folder” to “D:\Destination Folder\All” location.
  • Once you run the code, you will get your desired results.

Move all files of a folder using Excel VBA


1.3 Use For Loop to Move All Files from a Folder

We will move all files from one folder to another using For Loop. As we will use the For loop, there is no need to use the wildcard character. The VBA code is given below.

Sub MoveFilesForLoop()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim srcPath As String
    srcPath = "C:\SourceFolder\" ' Change the source folder path here
    Dim dstnPath As String
    dstnPath = "C:\DestinationFolder\All\" ' Change the destination folder path here
    Dim fileItem As Object
    For Each fileItem In fso.GetFolder(srcPath).Files
        fileItem.Move dstnPath
    Next fileItem
End Sub

Move all files of a folder using For loop in Excel VBA

Code Breakdown

 For Each fileItem In fso.GetFolder(srcPath).Files
        fileItem.Move dstnPath
    Next fileItem
  • The first line iterates through each file in the sourcePath folder.
  • Then the code moves files represented by FileFromFolder to the destinationPath folder.

The output after running the code will look like the following image.

Move all files of a folder using For loop in Excel VBA


Example 2 – Move Files to a New Folder

While moving files to a new directory, you may not have an existing directory and you need to make a directory prior to moving the files. Using VBA, you can create a folder and move the files. In this example, we will move the files to a newly created folder, we will create a new folder and set it as the destination folder for the files to be moved.

Enter the following VBA code in the module.

Sub MoveFileToNewFolder()
    Dim fso As Object
    Dim sourcePath As String
    Dim destinationPath As String
    Dim newFolder As String
    Dim fileName As Variant
   Set fso = CreateObject("Scripting.FileSystemObject")
sourcePath = "D:\Source Folder\"
destinationPath = "D:\Destination Folder\"
newFolder = "New Folder"
'Create new folder in destination folder
fso.CreateFolder (destinationPath & newFolder)
'Array of file names to move
fileName = Array("UDF.xlsx", "cap percentage.xlsx", "UDF 2.zip")
'Loop through each file and move to new folder
For i = LBound(fileName) To UBound(fileName)
    fso.MoveFile sourcePath & fileName(i), destinationPath & newFolder _
    & "\" & fileName(i)
Next i
End Sub

Move files to a new folder using Excel VBA

Code Breakdown

fso.CreateFolder (destinationPath & newFolder)
  • This line creates a new folder in the destinationPath
fileName = Array("UDF.xlsx", "cap percentage.xlsx", "UDF 2.zip")
  • This line creates an array that has three elements “xlsx“, “cap percentage.xlsx“, “UDF 2.zip“.
For i = LBound(fileName) To UBound(fileName)
            fso.MoveFile sourcePath & fileName(i), destinationPath & newFolder _
            & "\" & fileName(i)
Next i
  • This part of the code starts a loop that iterates through each element of the fileName The LBound and UBound functions return the lower and upper bound of the array.
  • The code moves files from the sourcePath folder to the newFolder that is created at the destinationPath.

Run the code and get your desired output.

Move files to a new folder using Excel VBA

Read More: Excel VBA to Loop Through Files in Folder and Rename


Example 3 – Move Selected Files from One Folder to Another

For this example, we will need a dataset with file names, sources and destinations.

  • From the dataset, select the file names you want to move. We have selected two files that will be moved to User Defined Function and Search Volume Folder.

Move selected files from one folder to another using Excel VBA

  • Go to the VBA code Module and enter the following code into it.
Sub MoveSelectedFiles()
    Dim fso As Object
    Dim sourceFileName As String, sourceFolderPath As String
    Dim destinFileName As String, destinFolderPath As String
    Dim fileName As String, destinFolderName As String
    Dim lastRow As Long, i As Long
    Dim selectedRange As Range, cell As Range
    Set fso = CreateObject("Scripting.FileSystemObject")
    sourceFolderPath = Range("C5").Value
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    Set selectedRange = Application.Selection
    For Each cell In selectedRange
        If Not Intersect(cell, Range("B5:B" & lastRow)) Is Nothing Then
            fileName = cell.Value
            destinFolderName = Range("D" & cell.Row).Value
            sourceFileName = sourceFolderPath & "\" & fileName
            destinFolderPath = destinFolderName & "\" & fileName
            If Not fso.FolderExists(destinFolderName) Then
                MsgBox ("Destination folder " & destinFolderName & " does not exist.")
                GoTo NextFile
            End If
            If Not fso.FileExists(sourceFileName) Then
                MsgBox ("File Not Found in " & sourceFileName)
            Else
                If fso.FileExists(destinFolderPath) Then
                    MsgBox (destinFolderPath & " already exists. Skipping file " & fileName)
                Else
                    fso.MoveFile Source:=sourceFileName, Destination:=destinFolderPath
                    MsgBox (sourceFileName & " moved to " & destinFolderPath)
                End If
            End If
NextFile:
        End If
    Next cell
End Sub

Code to Move selected files from one folder to another

Code Breakdown

sourceFolderPath = Range("C5").Value
lastRow = Cells(Rows.Count, "B").End(xlUp).Row
Set selectedRange = Application.Selection
  • The first line assigns the value of cell C5 to sourceFolderPath.
  • The next line calculates the last row within column B and assigns the value to lastRow
  • Set selectedRange = Application.Selection sets a variable named selectedRange to the currently selected range of cells.
For Each cell In selectedRange
        If Not Intersect(cell, Range("B5:B" & lastRow)) Is Nothing Then
            fileName = cell.Value
            destinFolderName = Range("D" & cell.Row).Value
            sourceFileName = sourceFolderPath & "\" & fileName
            destinFolderPath = destinFolderName & "\" & fileName
  • This part of the code iterates through selectedRange
  • Then it checks if there is any overlap between the current cell and range “B5:B” using Intersect
  • Press F5 on your keyboard.
  • As a result, the UDF 2 file will be moved to the User Defined Function

Move selected files from one folder to another using Excel VBA

  • The search file will be moved to the Search Volume Folder.

After Moving selected files from one folder to another


Example 4 – Move Files Based on File Names Using VBA in Excel

We will move files based on file names. We will use the following VBA code for this purpose. This code will move files if it finds the full match or partial match of a file name. The code will move the files that contain “UDF”  or “search” in their names.

Move files based on file names using Excel VBA

Code Breakdown

For Each srcFile In srcFolder.Files
        If InStr(srcFile.Name, "UDF") <> 0 Then
            fso.MoveFile srcFile.Path, targetFolderLocation & _
            "User Defined Function\" & srcFile.Name
        ElseIf InStr(srcFile.Name, "search") <> 0 Then
            fso.MoveFile srcFile.Path, targetFolderLocation & _
            "Search Volume Folder\" & srcFile.Name
        End If
    Next srcFile
  • The code starts a For Each loop that iterates through each file in the srcFolder.
  • Then it checks if the files in the srcFile contain the string “UDF”. If it does, then fso.MoveFile moves the file to the “User Defined Function” folder.
  • Similarly, if the file name contains “search”, then the file is moved to “Search Volume Folder”.

Run the code and go to the destination folders to see the results.

Move files based on file names using Excel VBA

Move files based on file names using Excel VBA

Read More: How to Use Excel VBA to List Files in Folder 


Example 5 – Move or Copy Files Based on a List

We can also move files based on a list or a cell value using VBA. In this example, we have a list of four files that we want to move to their corresponding destination folder.

files to be moved based on a list

Enter the following VBA code in the module.

Option Explicit
Sub MoveFilesBasedOnList()
    Dim fso As Object
    Dim sourceFileName As String, sourceFolderPath As String
    Dim destinFileName As String, destinFolderPath As String
    Dim fileName As String, destinFolderName As String
    Dim lastRow As Long, x As Long
    Set fso = CreateObject("Scripting.FileSystemObject")
    sourceFolderPath = Range("C5").Value
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    For x = 5 To lastRow
        fileName = Range("B" & x).Value
        destinFolderName = Range("D" & x).Value
        sourceFileName = sourceFolderPath & "\" & fileName
        destinFolderPath = destinFolderName & "\" & fileName
        If Not fso.FolderExists(destinFolderName) Then
            MsgBox ("Destination folder " & destinFolderName & " does not exist.")
            GoTo NextFile
        End If
        If Not fso.FileExists(sourceFileName) Then
            MsgBox ("File Not Found in " & sourceFileName)
        Else
            If fso.FileExists(destinFolderPath) Then
                MsgBox (destinFolderPath & " already exists. Skipping file " & fileName)
            Else
                fso.MoveFile Source:=sourceFileName, Destination:=destinFolderPath
                MsgBox (sourceFileName & " moved to " & destinFolderPath)
            End If
        End If
NextFile:
    Next x
End Sub

Code to Move files based on a list

Code Breakdown

For x = 5 To lastRow
        fileName = Range("B" & x).Value
        destinFolderName = Range("D" & x).Value
        sourceFileName = sourceFolderPath & "\" & fileName
        destinFolderPath = destinFolderName & "\" & fileName
  • The code uses a loop starting from the 5th row to the lastRow.
  • Then it assigns the values of column B to fileName and values of column D to destinFolderName.
  • The 4th line concatenates the “sourceFolderPath” variable with the “fileName” variable and a backslash to form the complete path. This complete path is assigned to the variable “sourceFileName“.
  • Similarly, the other one is assigned to the variable “destinFolderPath”.
  fso.MoveFile Source:=sourceFileName, Destination:=destinFolderPath
  • Then it moves the files from the path sourceFileName to destinFolderPath.

If you run this code, four MsgBox will appear with the message that a file from a folder is moved to another folder.

After Moving files based on a list

You can go to the destination folders to check the moved files.

Move files based on a list using Excel VBA

Move files based on a list using Excel VBA


How to Copy a File Using VBA in Excel

VBA can also be used to copy files in the same way as moving files.

Enter the following code into the module.

Sub CopySingleFile()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.CopyFile "D:\Source Folder\UDF.xlsx", _
    "D:\Destination Folder\User Defined Function\UDF.xlsx"
End Sub

code to Copy files

Code Breakdown

 fso.CopyFile "D:\Source Folder\UDF.xlsx", _
    "D:\Destination Folder\User Defined Function\UDF.xlsx"
  • This code copies the file “xlsx” from “D:\Source Folder” and paste it to “D:\Destination Folder\User Defined Function” location.

Run the VBA code and the file will be copied to the destination folder.

Copy files using Excel VBA


How to Move Folders Using Excel VBA

You can also move a whole folder using VBA code. We will move a Folder named Source Folder (D:\Source Folder) to a New Folder (D:\Destination Folder\New Folder). You can use the following VBA code to do this.

Sub MoveFolder()
    Dim fso As New FileSystemObject
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.MoveFolder "D:\Source Folder", "D:\Destination Folder\New Folder\"
End Sub

code to Move folders

Code Breakdown

  fso.MoveFolder "D:\Source Folder", "D:\Destination Folder\New Folder\"
  • The code moves the Source Folder located at “D:” to “D:\Destination Folder\New Folder

When you run the code, the whole Source Folder will be moved to the New Folder.

Move folders using Excel VBA


How to Move File from One Folder to Another and Overwrite Using Excel VBA

While moving a file, another file with the same name can exist in the destination folder. In this situation, we can overwrite the existing file with the new one.

Enter the following VBA code into the module.

Sub MoveFileOverwrite()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim sourcePath As String
    Dim destPath As String
    sourcePath = "D:\Source Folder\UDF.xlsx"
    destPath = "D:\Destination Folder\User Defined Function\UDF.xlsx"
    ' Check if the destination file already exists
    If fso.FileExists(destPath) Then
        ' Prompt a message box asking whether to overwrite the file or not
        Dim overwrite As VbMsgBoxResult
        overwrite = MsgBox("Do you want to overwrite the existing file?", _
        vbYesNo + vbQuestion, "File Exists")
        If overwrite = vbYes Then
            ' If user selects "Yes", delete the destination file
            fso.DeleteFile destPath
            fso.MoveFile sourcePath, destPath
            MsgBox "File moved successfully!", vbInformation, "Success"
        Else
            ' If user selects "No", then exit the sub
            Exit Sub
        End If
    Else
        ' If the destination file does not exist, simply move the source file
        fso.MoveFile sourcePath, destPath
        MsgBox "File moved successfully!", vbInformation, "Success"
    End If
End Sub

Move files from one folder to another overwrite

Code Breakdown

If fso.FileExists(destPath) Then
        ' Prompt a message box asking whether to overwrite the file or not
        Dim overwrite As VbMsgBoxResult
        overwrite = MsgBox("Do you want to overwrite the existing file?", _
        vbYesNo + vbQuestion, "File Exists")
        If overwrite = vbYes Then
            ' If user selects "Yes", delete the destination file
            fso.DeleteFile destPath
            fso.MoveFile sourcePath, destPath
  • The code first checks if a file exists in the destination folder using the FileExists
  • If a file exists, a MsgBox will appear that says “Do you want to overwrite the existing file?
  • If the user selects “Yes”, the code deletes the existing file using the “DeleteFile
  • Then it moves the file from the source folder to the destination folder using the “MoveFile
  • Once you run the code, a MsgBox will appear. It will ask “Do you want to overwrite the existing file?
  • Click on Yes to overwrite the file.

Move files from one folder to another overwrite using Excel VBA

  • A MsgBox will pop up that says “File moved successfully!

Move files from one folder to another overwrite using Excel VBA

  • Go to the destination folder to see the moved file.

Move files from one folder to another overwrite using Excel VBA

 


Download Practice Workbook


Related Articles

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Alif Bin Hussain
Alif Bin Hussain

Alif Bin Hussain earned a BSc in Civil Engineering from Bangladesh University of Engineering and Technology. As an engineering graduate, he has a deep passion for research and innovation. He loves to play with Excel. In his role as an Excel & VBA Content Developer at ExcelDemy, he not only solves tricky problems but also shows enthusiasm and expertise in handling tough situations with finesse, emphasizing his dedication to delivering top-notch content. He is interested in C, C++,... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo