Create Folder Recursively with Excel VBA

How to: create folders recursively using VBA code in Excel.

About

The below code can be used when you need your VBA code to create a folder in a locaiton that may not already exist. The function takes a directory path as a string input and creates each folder if they don’t already exist. It is compatible with both Local paths and Network share paths on windows.

Code

Below is the VBA code which can serve as a starting point for further development.

Explanation

First we check to see if the path (dir) is a local or network path. Then theSplit() function takes a string and splits it into an array by the passed delimiter, in our case \. From here we can iterate over the array and for each string (folder) and we try to create it. Using CreateObject("Scripting.FileSystemObject") we check to see if the folder exists with .FolderExists() and if not create it with .CreateFolder. Finally we check to see if the location exists and return True if it does.

The Sub callFunction() shows us 2 example calls.

Links

  • Split() function link
  • Scripting.FileSystemObject object link

About the author

Leave a Reply

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