How to: create folders recursively using VBA code in Excel.
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.
Below is the VBA code which can serve as a starting point for further development.
First we check to see if the path (
dir) is a local or network path. Then the
Split() 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.
callFunction() shows us 2 example calls.