Get our FREE VBA eBook of the 30 most useful Excel VBA macros.

Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.

Claim your free eBook


VBA code to copy, move, delete and manage files

VBA Code Snippets

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

Download the example file

I recommend you download the example file for this post.  Then you’ll be able to work along with examples and see the solution in action, plus the file will be useful for future reference.

Download Icon
Download the file: 0041 VBA copy, move, delete and manage files.zip

Check if a file exists

If any actions are performed on a file that does not exist, the VBA code will error.  As a result, checking for a file’s existence can be one of the most common action we perform.

The code below will display True or False in a message box to indicate if the file exists.

Sub CheckIfFileExists()

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

End Sub

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

Sub PerformActionIfFileExists()

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 displays a message box
    MsgBox filePath & " exists."

Else

    'Insert actions if the file does not exist
    'This example displays a message box
    MsgBox filePath & " does not exist."

End If

End Sub

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.

Sub UseTheFunction()

Dim myFile As String

myFile = "C:\Users\marks\Documents\Folder\FileName.xlsx"

'Call the reusable function to check for file existence
If DoesFileExist(myFile) = True Then

    'Insert action for if the file exists
    'This example displays a message box
    MsgBox "The file exists."

End If

End Sub

Rename a file

The code below renames a file.

Sub RenameAFile()

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

End Sub

If the target filename is already an existing file, the code will error.  Therefore, it is good practice to check if the source and target file names are already in use.

Check out this post for more examples of using VBA to rename files.

Moving a file

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

Sub MoveAFile()

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

End Sub

Copying a file

Copying a file retains the existing file, but creates a duplicate version of it in a new location.

Sub CopyAFile()

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

End Sub

If the target filename is already an existing file, the code will error.  Therefore, it is good practice to check if the source and target file names are already in use.

Delete files

Deleting files removes them completely.  Files deleted using VBA are not sent to the recycle bin, and since there is no undo functionality it can be quite dangerous.  Take extra care to ensure the code does what you expect it to.

The following code deletes a specific file.

Sub DeleteSpecificFile()

'Delete a specific file
Kill "C:\Users\marks\Documents\Folder\DeleteMe.xlsx"

End Sub

The code below deletes files using a wildcard.  In this circumstance, it deletes all files with a .xlsx file extension.

Sub DeleteFilesWithWildcards()

'Delete all .xlsx files using the * wildcard character
Kill "C:\Users\marks\Documents\Folder\*.xlsx"

End Sub

The example below deletes all the files in a folder by using wildcard characters.

Sub DeleteAllFilesInFolder()

'Delete all files from a folder using two * wildcard characters
Kill "C:\Users\marks\Documents\Folder\*.*"

End Sub

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

Each files has specific attributes, for example, they can be read-only, hidden or system files etc..

The code below checks if a file is read-only.

Sub GetFileAttributes()

Dim myFile As String

myFile = "C:\Users\marks\Documents\Folder\ReadOnlyFile.xlsx"

'If the file is Read-Only, display message box
If (GetAttr(myFile) And vbReadOnly) <> 0 Then

    MsgBox "The file is Read only"

End If

End Sub

To check for other attributes, replace vbReadOnly in the code above with the required settings.

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

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn't until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I'm guessing the examples in this post don't exactly match 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:

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

  1. Danny Doyle says:

    Good morning Mark,

    Thank you so much for posting the handy set of VBA routine for managing files, some of which will I will certainly be using to enhance a user-interface to automate an Excel -to-Word application I am developing.

    As I can imagine you are inundated with request for advice, I will certainly understand if you are unable to respond to this thank-you note, but on the off chance you might be able to offer some help, here’s an issue I am trying to deal with:

    Although I have successfully developed a routine to extract text items from an excel workbook to a Word document using bookmarks in the Word document itself, I am having problem with a copying a chart
    (graph). Although the the actual extraction from Excel and transfer is working fine, the “layout” of the chart defaults to “In line with text” option and disrupts the format of the textual content of the document. The issue is easily resolvable by manually clicking on the transferred chart and then, from the displayed Layout options, selecting in “Front of text” one. Doing this enables the chart to be moved (floated) into the desired position . I believe there must be a simple way of programmatically conditioning the “Front of text” option, but so far I haven’t been able to figure out how to do it, so any help/advice you might be able to offer would be gratefully received and I’m sure would be appreciated by other coders you might be able to assist.

    Many thanks in advance.

    Best regards,

    Danny

    • Excel Off The Grid says:

      Hi Danny – It’s not something I have ever tried. Have you tried to use the Macro recorder in Word to capture the relevant code?

Leave a Reply

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