Check If File Exits in the specified folder in Excel VBA. If it is available then Delete file from the specified folder. In the following tutorial we have explained step by step instructions.
Let us see an example macro VBA code for checking If File Exits or not. If it exists then Delete. In below example we are specifying folder path and file name which we are looking for. You can change these as per your requirements. After that checking specified folder is exists or not. If it is exists checking, we are looping through each file. While looping we are checking every file and specified file is same. If it is same then deleting the specified file from that folder.
'VBA Checking If File Exits then Delete Sub VBAF1_Check_If_File_Exits_then_Delete() 'Variable declaration Dim sFolderPath As String Dim sFileName As String, oFile As Object 'Define Folder Path sFolderPath = "C:\VBAF1\Test\" 'Specify File Name which we we are looking for sFileName = "Sample.xlsx" 'Create FSO Object Set oFSO = CreateObject("Scripting.FileSystemObject") 'Check Specified Folder exists or not If oFSO.FolderExists(sFolderPath) Then 'Loop through each file in a specified folder For Each oFile In oFSO.GetFolder(sFolderPath).Files 'Check Specified is exists If oFile.Name = sFileName Then 'If file is available delete oFile.Delete End If Next End If End Sub
Here are the instructions to use above macro in Visual basic editor.
- Open Visual Basic Editor(VBE) by clicking Alt +F11
- Go to code window by clicking F7
- Copy above specified macro or procedure
- Paste above copied code in code window
- Run macro by clicking F5 or Run command
- Check macro output in the specified folder. Specified file deleted (If it is available).
You can also learn complete details like syntax, example and etc by clicking on the following buttons.