Access Excel VBA delete folder if folder exists

This tutorial explains how to use Access / Excel VBA to delete folder if folder exists already.

Access Excel VBA delete folder if folder exists

Suppose you want to write a Macro to export files to a folder. There could be problem if the folder already contains the files you want to export. To avoid this, you probably want to delete the folder and create a new folder before exporting the files. Alternatively, you can also delete all files in the folder.

In order to delete a folder, you can use the FSO Folder Methods.

folderpath = "C:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.deleteFolder (folderpath)

To check if folder already exists, use FSO.FolderExists Method

FSO.FolderExists(folderpath) = True

To delete folder if folder exists already, we can combine the above

folderpath = "C:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(folderpath) = True Then
    FSO.deleteFolder (folderpath)
End If

Finally to recreate the deleted folder, add createFolder Method at the end of the Procedure

Public Sub delFolder()
    folderpath = "C:\test"
    Set FSO = CreateObject("Scripting.FileSystemObject")
    If FSO.FolderExists(folderpath) = True Then
        FSO.deleteFolder (folderpath)
    End If
    FSO.createFolder (folderpath)
End Sub

 

Wyman W
Wyman is a Business Analyst based in Hong Kong, specialized in business analysis, project management, and also creating custom Function and Sub solutions, and is proficient in report automation with Access.

He is also a:
- Microsoft Most Valuable Professional (Excel)
- Microsoft Community Contributor
- Microsoft Office Specialist in Access / Excel
- Microsoft Specialist in MS Project
- Microsoft Technical Associate
- Microsoft Certified Professional
- IBM SPSS Specialist

Leave a Reply

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