DeleteFile Method

Deletes a specified file.

Syntax

object.DeleteFile (filespec)

Arguments:

  • Object: Required. Always the name of a FileSystemObject.
  • Filespec: Required. The name of the file along with absolute path to delete.
  • Force: Optional. Boolean value that is true if files with the read-only attribute set are to be deleted; false (default) if they are not.

Remarks

An error occurs if no matching files are found. The DeleteFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.

The following example illustrates the use of the DeleteFile method.

Example 1:

Sub DeleteSingleFile()
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.DeleteFile("C:\example1.txt")   ' Deletes the specified file.
     Set fso = Nothing
End Sub

Call DeleteSingleFile

Note:

Use FileExists method to check the existence of the file and then use DeleteFile.

Example 2:

Sub CheckAndDeleteFile()
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists("C:\example2.txt") Then
        fso.DeleteFile("C:\example2.txt")   ' Deletes the specified file.
     End If
    Set fso = Nothing
End Sub