3 Ways to Create Missing Subfolders in VBA

If you need to generate multiple levels of subfolders using VBA, these three functions will each get the job done.

3 Ways to Create Missing Subfolders in VBA

Here are three functions that will verify a path exists and attempt to create the path (including subfolders) if it does not:

  1. VerifyFolder(): uses recursion and the FileSystemObject
  2. MakeSurePathExists(): uses the MakeSureDirectoryPathExists API function
  3. EnsurePathExists(): uses the Unicode-safe SHCreateDirectoryExW API function

VerifyFolder()

I've used this function for 15 years, so it is well-tested.  It also makes for a great introduction to the topic of recursion.  That said, the Windows API options almost certainly perform better.

MakeSurePathExists()

This approach is based on an API function–MakeSureDirectoryPathExists–that does exactly what it says.  There is something to be said for that sort of simplicity.

That said, its major limitation is that it does not support Unicode paths.

EnsurePathExists()

This approach relies on the SHCreateDirectoryExW API function to create directories if they do not exist.


What Should You Use?

The short answer? EnsurePathExists.

I recommend the EnsurePathExists function as it provides full Unicode-compatibility along with the superior performance of a Windows API function.

However, if you want to learn more about recursion, the VerifyFolder function is a great practical example of how recursion can make certain classes of problems much easier to solve.


Referenced articles

Recursion Demystified: Creating Subfolders
Recursion: it’s not just for calculating factorials any more! A practical example of using recursion to create multiple missing subfolders.
MakeSurePathExists: Using the Windows API to Create Missing Subfolders in VBA
A Windows API function makes verifying (and creating, if necessary) a full folder hierarchy dead simple.
EnsurePathExists: A Unicode-Safe Way to Create Missing Subfolders in VBA
The EnsurePathExists function--based on the API function SHCreateDirectoryExW--is the ultimate tool for verifying and creating folder structures.

Image by Gosia K. from Pixabay

All original code samples by Mike Wolfe are licensed under CC BY 4.0