VBA Delete Text Files

VBA Delete Text Files

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.

VBA Delete Text File Example
VBA Delete Text File Example

Instructions to use Macro

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
  • You can see output in the immediate window
  • you can find above specified input and output screenshot for your reference and better understand.

Related Articles

You can also learn complete details like syntax, example and etc.

VBA Text Files Complete Reference Tutorial

Leave a Comment

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