VBA code to copy, move, delete and manage files

VBA Code Snippets

Automating processes with VBA can involve copying, moving, deleting and managing a lot of files.  Thankfully, VBA has a number of built-in functions to undertake these tasks.  These files do not necessarily need to be Excel workbooks, they can be any file type.

Check if a file exists

If any actions are performed on a file which does not exist, the VBA code will error.  As a result, checking for file existence is often the most common action.

The code below will print True or False to the immediate window to indicate if the file exists.

'Check if a file exists
Debug.Print Dir("C:\Users\marks\Documents\Folder\Text.xlsx") <> ""

The code below uses an If statement to carry out different actions depending on if the file does or does not exist.

'Check if a file exists
Dim filePath As String
filePath = "C:\Users\marks\Documents\Folder\FileName.xlsx"

If Dir(filePath) <> "" Then

    'Insert action for if the file exists
    'This example prints to the immediate window
    Debug.Print filePath & " exists."


    'Insert actions if the file does not exist
    'This example prints to the immediate window
    Debug.Print filePath & " does not exist."

End If

When regularly checking for the existence of files, it can be easier to have a reusable function within a Module to be called upon when required.

'Reusable function to check if a file exists
Function doesFileExist(filePath) As Boolean

doesFileExist = Dir(filePath) <> ""

End Function

The code below shows how to call the reusable function as part of an If statement

'Call the reusable function to check for file existence
If doesFileExist("C:\Users\marks\Documents\Folder\FileName.xlsx") = True Then

    'Insert action for if the file exists
    'This example prints to the immediate window 
    Debug.Print "The file exists."

End If

Rename a file

'Rename a file
Name "C:\Users\marks\Documents\Folder\CurrentFileName.xlsx" As "C:\Users\marks\Documents\Folder\NewFileName.xlsx"

Moving a file

The code to move a file is the same syntax as the code to rename a file.

'Move a file
Name "C:\Users\marks\Documents\FileName.xlsx" As "C:\Users\marks\Documents\New Folder\FileName.xlsx"

Generate accurate VBA code in seconds with AutoMacro


AutoMacro is a powerful VBA code generator that comes loaded with an extensive code library and many other time-saving tools and utilities.

Whether you’re an experienced coder looking to save time, or a newbie just trying to get things to work, AutoMacro is the tool for you.

Copying a file

'Copy a file
FileCopy "C:\Users\marks\Documents\Folder\Original File.xlsx", "C:\Users\marks\Documents\New Folder\Copied File.xlsx"

Delete files

'Delete a specific file
Kill "C:\Users\marks\Documents\Folder\DeleteMe.xlsx"
'Delete all .xlsx files using the * wildcard character
 Kill "C:\Users\marks\Documents\Folder\*.xlsx"
'Delete all files from a folder using two * wildcard characters
 Kill "C:\Users\marks\Documents\Folder\*.*"

Common wildcard characters are:

Character Description
* (asterisk) Any number of characters
? (question mark) Any individual characters

The example below applies the * (asterisk) and ? (question mark) wildcard characters

'Delete all .xlsx or .xlsm files from a folder, but not .xls files
'as the ? wildcard must be atleast on character in length
 Kill "C:\Users\marks\Documents\Folder\*.xls?"

Get file attributes

'If the file is Read-Only, display message box
If (GetAttr("C:\Users\marks\Documents\Folder\ReadOnlyFile.xlsx") And vbReadOnly) <> 0 Then
    MsgBox "The file is Read only"
End If

It is possible to check for other file attributes, by replacing vbReadOnly in the code above:

VBA Name of attribute Enumerator Description
vbNormal 0 Files with no attributes (default setting)
vbReadOnly 1 Read-only files
vbHidden 2 Hidden files
vbSystem 4 System files
vbVolume 8 Volume label
vbDirectory 16 Directories

Don’t forget:

If you’ve found this post useful, or if you have a better approach, then please leave a comment below.

Do you need help adapting this to your needs?

I’m guessing the examples in this post didn’t exactly meet your situation.  We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs.  By taking the time to understand the techniques and principles in this post (and elsewhere on this site) you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic.  You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office.  It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community.  Remember, the people on these forums are generally giving their time for free.  So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner.   They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

3 thoughts on “VBA code to copy, move, delete and manage files

  1. Abou says:

    Dear All,

    First of all thank you to helped me to have solved the issue in my previous code. Now what I would like to do is to move some specific files containing a number in the name of the file ( from a folder to another location. I tried but unsucessful.

    Would it be possible to help
    Many thanks
    Bets regards

    Sub Test()

    Dim R As Range
    Dim SourcePath As String, DestPath As String, FName As String

    Set fname00 = Range(“”E1″”)
    Set fname01 = Range(“”E2″”)
    SourcePath = “”C:\DGI\Commun\R\10.R\11.Co\”” & fname00 & “”\”” & fname01 & “”\””
    DestPath = “”C:\DGI\Commun\R\10.R\11.C\Tobesent\””
    ‘Visit each used cell in column F
    For Each R In Range(“”G2″”, Range(“”G”” & Rows.Count).End(xlUp))
    ‘Search the file with the file mask from the cell (Note: can contain wildcards like *.xls)
    FName = Dir(SourcePath & R)
    ‘Loop while files found
    Do While FName “”””
    ‘Copy the file
    FileCopy SourcePath & FName, DestPath & FName
    ‘Search the next file
    FName = Dir()
    End Sub

    • Excel Off The Grid says:

      Hi Abou,

      Have you looked at this post:

      Do While FName would surely need to be:
      Do While FName <> “”

      Do the values in Cells G2 downwards include a slash ( \ ) at the end?

      The following line of code would need to include R somewhere
      FileCopy SourcePath & FName, DestPath & FName
      It should be something like:
      FileCopy SourcePath & R & FName, DestPath & FName

      Where is the code failing?

      As from our previous communications. Try to use Debug.Print to check that the variables at each point in the code are what they are meant to be.

  2. George Fortech says:

    Thanks for this post. Used these techniques from MS Access VBA successfully. Helped me solve an issue for important client…

Leave a Reply

Your email address will not be published. Required fields are marked *