VBA Delete Workbook in a folder in Excel. Delete Workbook in Excel VBA. We can delete Excel Workbook using Kill statement or DeleteFile method of file system object(FSO). Find example macros, screenshots and instructions to use macros for your reference in the following chapter. In the following examples before deleting files, check whether files are exists or not.
Let us see the syntax to Delete Workbook in Excel VBA.
Method 1: Here is the first method to delete a Workbook using Kill statement.
Read more details and examples about Kill statement by clicking on the following link.
Method 2: Here is the second method to delete a Workbook using DeleteFile method of File System Object(FSO).
Let us see the example macro to delete Excel Workbook using VBA Kill function.
'Delete Workbook in Excel VBA using Kill Statement Sub VBA_Delete_Workbook_Excel_Using_Kill() 'Variable declaration Dim sWorkbook As String sWorkbook = "C:\Someswari\VBAF1\SampleWorkbook.xls" Application.DisplayAlerts = False 'Delete Workbook Kill sWorkbook Application.DisplayAlerts = True MsgBox "Specified Workbook has deleted successfully.", vbCritical, "VBAF1" End Sub
Note: If specified workbook doesn’t exists, it displays an error message. I.e Run time error – “File not found” .
Let us see the example macro to delete Excel Workbook using VBA DeleteFile method of File System Object(FSO). Here first we are checking whether file exists or not before deleting. If file exists, then deletes the specified file. Otherwise it displays message.
'Delete Workbook in Excel VBA using DeleteFile method of FSO Sub VBA_Delete_Workbook_Excel_Using_FSO() 'Variable declaration Dim FSO Dim sWorkbookName As String 'File Name to delete sWorkbookName = "C:\Someswari\VBAF1\SampleWorkbook.xls" 'Set Object for file system object Set FSO = CreateObject("Scripting.FileSystemObject") 'Before deleting check file exists or not If FSO.FileExists(sWorkbookName) Then 'If file exists, It will delete the file from source location FSO.DeleteFile sWorkbookName, True MsgBox "Workbook has deleted successfully.", vbInformation, "VBAF1" Else 'If file does not exists, It will display following message MsgBox "Specified Workbook was not found", vbInformation, "Not Found!" End If End Sub
Output: You can notice specified Workbook has deleted from the specified folder.
You can refer the following link for the step by step instructions.
Click on the following links of the useful resources. These helps to learn and gain more knowledge.