Skip to main content

 How to check if a folder exists and if not create it?

Have you ever tried to check if a folder exists or not from Excel worksheet? In this article, I will talk about checking if a folder exists in a specified path, if not, the folder will be created automatically under the path.

Check if a folder exists in a specific file path with VBA code

Create the folder if not exists in a specific file path with VBA code


arrow blue right bubble Check if a folder exists in a specific file path with VBA code

The following VBA code may help you to check if a folder exists in a specific file path, please do as this:

1. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window.

2. Click Insert > Module, and paste the following code in the Module Window.

VBA code: Check if a folder exists in a specific file path:

Sub Test_Folder_Exist_With_Dir()
'Updateby Extendoffice
    Dim sFolderPath As String
    sFolderPath = "C:\Users\DT168\Desktop\Test folder"
    If Right(sFolderPath, 1) <> "\" Then
        sFolderPath = sFolderPath & "\"
    End If
    If Dir(sFolderPath, vbDirectory) <> vbNullString Then
        MsgBox "Folder exist", vbInformation, "Kutools for Excel"
    Else
        MsgBox "Folder doesn't exist", vbInformation, "Kutools for Excel"
    End If
End Sub

Note: In the above code, you should change the folder path and name C:\Users\DT168\Desktop\Test folder to your needed.

3. Then press F5 key to run this code, you will get the following results:

doc folder exist 1


arrow blue right bubble Create the folder if not exists in a specific file path with VBA code

Check if a folder exists in a file path, if not, to create it under this specific file path, the following VBA code may help you to finish this job.

1. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window.

2. Click Insert > Module, and paste the following code in the Module Window.

VBA code: Create a folder if not exists in a file path:

Sub MakeMyFolder()
'Updateby Extendoffice
    Dim fdObj As Object
    Application.ScreenUpdating = False
    Set fdObj = CreateObject("Scripting.FileSystemObject")
    If fdObj.FolderExists("C:\Users\DT168\Desktop\Test folder") Then
        MsgBox "Found it.", vbInformation, "Kutools for Excel"
    Else
        fdObj.CreateFolder ("C:\Users\DT168\Desktop\Test folder")
        MsgBox "It has been created.", vbInformation, "Kutools for Excel"
    End If
    Application.ScreenUpdating = True
End Sub

Note: In the above code, you should change the folder path and name C:\Users\DT168\Desktop\Test folder to your needed.

3. After pasting the code, and press F5 key to run it:

(1.) If the folder exists, a prompt box will pop out as following screenshot shown:

doc folder exist 2

(2.) If the folder does not exist, it will be created under the specific path at once, and a prompt box will pop out to remind you the folder has been created, see screenshot:

doc folder exist 3

Best Office Productivity Tools

🤖 Kutools AI Aide: Revolutionize data analysis based on: Intelligent Execution   |  Generate Code  |  Create Custom Formulas  |  Analyze Data and Generate Charts  |  Invoke Kutools Functions…
Popular Features: Find, Highlight or Identify Duplicates   |  Delete Blank Rows   |  Combine Columns or Cells without Losing Data   |   Round without Formula ...
Super Lookup: Multiple Criteria VLookup    Multiple Value VLookup  |   VLookup Across Multiple Sheets   |   Fuzzy Lookup ....
Advanced Drop-down List: Quickly Create Drop Down List   |  Dependent Drop Down List   |  Multi-select Drop Down List ....
Column Manager: Add a Specific Number of Columns  |  Move Columns  |  Toggle Visibility Status of Hidden Columns  |  Compare Ranges & Columns ...
Featured Features: Grid Focus   |  Design View   |   Big Formula Bar    Workbook & Sheet Manager   |  Resource Library (Auto Text)   |  Date Picker   |  Combine Worksheets   |  Encrypt/Decrypt Cells    Send Emails by List   |  Super Filter   |   Special Filter (filter bold/italic/strikethrough...) ...
Top 15 Toolsets12 Text Tools (Add Text, Remove Characters, ...)   |   50+ Chart Types (Gantt Chart, ...)   |   40+ Practical Formulas (Calculate age based on birthday, ...)   |   19 Insertion Tools (Insert QR Code, Insert Picture from Path, ...)   |   12 Conversion Tools (Numbers to Words, Currency Conversion, ...)   |   7 Merge & Split Tools (Advanced Combine Rows, Split Cells, ...)   |   ... and more

Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time.  Click Here to Get The Feature You Need The Most...

Description


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
Comments (12)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Buonasera,

Non conosco il Vs. sito e mi sono imbattuto per caso su questa pagina.
Ho letto quanto scritto sopra e se è possibile avrei bisogno del Vs. aiuto.
Mi occorrerebbe una macro che in un percorso variabile ad un Host facente parte della stessa lan verifiche se è aperto un file exel dal nome variabile, e nel caso sia aperto chiuda il file e cancella tutto il contenuto della cartella compreso il file stesso.
Provo a spiegarmi meglio:
nel percorso :\\host01\Users\utente\Desktop\liste\Nome_Cognome_Gennaio\Operatore_16_Gennaio.xlsm
è presente un file excel dal nome : Operatore_16_Gennaio.xlsm

Il percorso non sempre è lo stesso così come il nome del file excel. Infatti il percorso cambia solo nel Nome_Cognome,es: :\\host01\Users\utente\Desktop\liste\Tizio_Caio_Gennaio\Operatore_16_Gennaio.xlsm) mentre nel file cambia solo il numero dell'operatore (Es: :\\host01\Users\utente\Desktop\liste\Sempronio_zeta_Gennaio\Operatore_15_Gennaio.xlsm.)

E' possibile avere una macro che fa quanto descritto sopra?

Ringrazio anticipatamente
This comment was minimized by the moderator on the site
How to create folder in desktop with vba whenever the excel book is opened, if exist, ignore.
Message if create new folder, silent if the folder exist.

Private Sub Workbook_Open()

Dim cOb As Variant
Dim FolderName As String, FolderExists As String
FolderName = "C:\Users\" & Environ("username") & "\Desktop\MyFolder\" '--->Change folder name to suit.
FolderExists = Dir(FolderName, vbDirectory)

Application.ScreenUpdating = False

If FolderExists = vbNullString Then
MsgBox "The desktop folder doesn't exist. Creating a new folder now.", vbExclamation, "INFORMATION"
cOb = CreateObject("wscript.shell").specialfolders("Desktop") & "\" & "MyFolder" '--->Change folder name to suit.
MkDir cOb
Else: Exit Sub
End If

Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
How to create folder in desktop with vba whenever the excel book is opened, if exist, ignore.
Message if create new folder, silent if the folder exist.


Private Sub Workbook_Open()

Dim cOb As Variant
Dim FolderName As String, FolderExists As String
FolderName = "C:\Users\AAAAA\Desktop\A New Folder" '---->Change folder name to suit. Change the AAAAA to your requirement.
FolderExists = Dir(FolderName, vbDirectory)

Application.ScreenUpdating = False

If FolderExists = vbNullString Then
MsgBox "The desktop folder doesn't exist. Creating a new folder now.", vbExclamation, "INFORMATION"
cOb = CreateObject("wscript.shell").specialfolders("Desktop") & "\" & "A New Folder" '--->Change folder name to suit.
MkDir cOb
Else: Exit Sub
End If

Application.ScreenUpdating = True

End Sub

This comment was minimized by the moderator on the site
excelente, me sirvió mucho el Objeto. Uso para carpetas como archivos. Muchas gracias
This comment was minimized by the moderator on the site
Hi, This works great, would there be any chance that the folder name used when checking if a folder already exists is derived from a cell within the spreadsheet, say A2??

I use a template spreadsheet which is updated automatically from another source, so cell A2 constantly changes which requires new folders being created in the same name.

Also, could there be such a command which does the above but also saves the active spreadsheet in the found / created folder?

Any hope? TIA
This comment was minimized by the moderator on the site
I'm running this macro, but in the step to create the folder, the process goes down.

can you help me????


'Comprobar si la carpeta existe

Dim ruta As String
Dim libro As String

M = ActiveWorkbook.Name

ruta = Application.Workbooks(M).Sheets("Diccionario").Range("B5").Value

If Right(ruta, 1) <> "\" Then
ruta = ruta & "\"
End If
If Dir(ruta, vbDirectory) <> vbNullString Then
MsgBox "Folder exist, please continue"
Else
MsgBox "Folder doesn't exist"
End If

'Crea la carpeta que necesitas

Dim fdObj As Object
Dim folder As String

folder = Application.Workbooks(M).Sheets("Dicionario").Range("B5").Value (here is where the process falls)

Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If fdObj.FolderExists(folder) Then
MsgBox "Found it, pleace continue."
Else
fdObj.CreateFolder (folder)
MsgBox "It has been created."
End If
Application.ScreenUpdating = True
This comment was minimized by the moderator on the site
Super Thanks!
This comment was minimized by the moderator on the site
Thanks Man, work amazing
This comment was minimized by the moderator on the site
This is really helpful! thanks!
This comment was minimized by the moderator on the site
Great article. Just what I was looking for :)
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
Rate this post:
0   Characters
Suggested Locations