VBA Delete Text Files using Kill statement or DeleteFile method of file system object(FSO). In the following tutorial let us learn how to delete text file in two different methods.
Add Reference: Microsoft scripting Runtime
Please click on following link to know about how to add reference of Microsoft scripting Runtime.
Create Microsoft Scripting Runtime Library Reference
DeleteFile Method to Delete Text File in Excel VBA
Delete file using DeleteFile Method of file system object. The following macro deletes the specified text file.
'VBA DeleteFile using FSO Delete file method Sub VBAF1_To_Delete_TextFile_Using_FSO_DeleteFile_Method() 'Variabledeclaration Dim oFSO As New FileSystemObject Dim sFile As String Dim myTextStream As TextStream 'Specify text file path to open sFile = "C:\VBAF1\CreateTextFile.txt" 'Text file to delete oFSO.DeleteFile sFile, False End Sub
Kill Statement to Delete Text File in Excel VBA
Delete a file using kill statement.
'VBA Delete File using Kill Statement Sub VBAF1_To_Delete_TextFile_Using_Kill_Statement() 'Variable declaration Dim FileNum As Integer Dim sFile As String 'Specify text file path to delete sFile = "C:\VBAF1\sample.txt" 'Check Text file is available or not If Len(Dir(sFile)) > 0 Then 'Delete specified text file MsgBox "File found and deleted.", vbInformation, "VBAF1" Kill sFile Else 'Display message if file is not available MsgBox "File not found.", vbInformation, "VBAF1" End If End Sub
Explanation:If specified file is available it deletes. Otherwise it display message on the screen. Here is a screen shot for your reference. You can see output in the immediate window.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog