Creating, deleting and renaming folders is a common requirement when automating processes with VBA. The code snippets below should be sufficient to complete the most common folder tasks.
All the code examples below use the built-in Dir() function and its derivatives. The File System Object methods are not covered in this post but will be covered at a future point.
Check if a folder exists
Referencing a folder which does not exist will result in an error, therefore it is often necessary to check if a folder exists before carrying out any other actions.
'Check if a folder exists Dim folderPath As String folderPath = "C:\Users\marks\Documents\Folder" If Dir(folderPath, vbDirectory) <> "" Then 'Insert action for if the folder exists 'This example prints to the immediate window Debug.Print folderPath & " exists." Else 'Insert actions if the folder does not exist 'This example prints to the immediate window Debug.Print folderPath & " does not exist." End If
vbDirectory is the attribute of a folder. The code above can be adapted to check for other types of files too.
|VBA Name of attribute||Enumerator||Description|
|vbNormal||0||Files with no attributes (default setting)|
For checking folder existence within another procedure, it is often easier to have a reusable function, which can be called upon when required.
'Reusable function to check if a folder exists Function doesFolderExist(folderPath) As Boolean DoesFolderExist = Dir(folderPath, vbDirectory) <> "" End Function
The following VBA code calls the doesFolderExist function from above and prints True (the folder exists) or False (the folder does not exist) to the Immediate window.
'Call the reusable function to check for folder existence Debug.Print doesFolderExist("C:\Users\marks\Documents\Folder")
The following VBA code calls the doesFolderExist function from above for use within an If statement.
'Check if a folder exists calling the doesFolderExist function Dim folderPath As String folderPath = "C:\Users\marks\Documents\Folder" If doesFolderExist(folderPath) = True Then 'Insert action for if the folder exists 'This example prints to the immediate window Debug.Print folderPath & " exists." Else 'Insert actions if the folder does not exist 'This example prints to the immediate window Debug.Print folderPath & " does not exist." End If
Do you know the fastest way to learn foreign languages? It is to read, write, speak, and think in that language as often as possible. Apart from speaking, programming languages are no different. The more you immerse yourself in that language, the faster you will pick it up.
Therefore, what most people like you need is lots of examples that you can practice. That is why the 100 Excel VBA Macros eBook exists. It’s the book for all Excel users who want to learn how to read and write Excel macros, save time, and stand out from their peers. The book contains:
- 100 example codes to practice reading and writing macros that will embed the language into your thinking.
- An introduction to macros in Excel to ensure you can implement the VBA code in the book even if you have no prior knowledge.
- Consistent code layout between examples to enable you to understand the structure and easily customize the code to meet your needs.
- Downloadable workbook containing all the source code, so the examples can be added to your project to give you the benefit of VBA straight away.
Create a new folder
The VBA code below will create a new folder. If the folder already exists, it will not overwrite it, but it will display an error. The function will only create the last folder in the file path, all the parent folders must already exist.
'Create a new folder MkDir "C:\Users\marks\Documents\New folder"
The avoid an error, the code below will check if a folder exists before trying to create it.
'Create a folder if it does not already exist, if it does, do nothing Dim folderPath As String folderPath = "C:\Users\marks\Documents\New Folder" 'Check if the folder exists If Dir(folderPath, vbDirectory) = "" Then 'Folder does not exist, so create it MkDir folderPath End If
As the Dir() function will only create a single folder, the code below loops through the individual folder names in the path and calls the Dir() function to create any missing folders and subfolders.
'Create all the folders in a folder path Dim folderPath As String Dim individualFolders() As String Dim tempFolderPath As String Dim arrayElement As Variant 'The desired folder path folderPath = "C:\Users\marks\Documents\New Folder\New Folder\New Folder\New Folder" 'Split the folder path into individual folder names individualFolders = Split(folderPath, "\") 'Loop though each individual folder name For Each arrayElement In individualFolders 'Build string of folder path tempFolderPath = tempFolderPath & arrayElement & "\" 'If folder does not exist, then create it If Dir(tempFolderPath, vbDirectory) = "" Then MkDir tempFolderPath End If Next arrayElement
Delete a folder
The RmDir function will delete a folder. However, it is limited as it will only delete an empty folder. All the files within the folder will need to be deleted first. Using the File System Object method (which is not covered in this post) it is possible to delete folders and their contents.
'Delete a folder Dim folderPath As String folderPath = "C:\Users\marks\Documents\Delete Folder" 'Ensure the folder path as a "\" at the end of the string 'Required for deleting the files using wildcards If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\" 'Use wildcards to delete all the files in the folder Kill folderPath & "*.*" 'Delete the now empty folder RmDir folderPath
If the folder does not exist the RmDir function will display an error. Refer to the first section of this post to check for existence
Rename a folder
The VBA code below will re-name a folder, and even move the contents of the entire folder to another location.
'Rename a folder Name "C:\Users\marks\Documents\Folder" As "C:\Users\marks\Documents\Renamed Folder"
To use this example code, it may be necessary to check if the old folder name exists and the new folder name does not exist.
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.
By entering your email address you agree to receive emails from Excel Off The Grid. We’ll respect your privacy and you can unsubscribe at any time.
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:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- 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.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts: