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 files which support this post, as you’ll be able to work along with examples. This is the best way to learn. You’ll be able to see the solutions in action, plus the file will be useful for future reference. The support files are available for FREE to newsletter subscribers.
Click below to subscribe and gain access to the subscriber area. You will also receive:
- My favorite tips and tricks direct to your inbox
- Exclusive content (which is only available to subscribers)
- FREE tools and downloads
If you’re already a subscriber, click here to log-in to the subscriber downloads area.
The filename for this post is 0041 VBA copy, move, delete and manage files.zip
Contents
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.
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
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
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 |
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: What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
Thank you for taking the time to create the small VBA code. They are a great starting point.
I appreciate your knowledge!!!
it give me great help. you made very useful and detailed instruction.
Thank you 🙂
How about if the file does not have extentions, what syntax I should put on, because I put *.* in dir syntax, the program cannot recognize the file
Interesting, I’ve not tried this before.
When I tested it the macro still appeared to delete files in the folder, even if it didn’t have a flie extension. Can you give an example of what you’re trying to achieve.