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