Table of Content

TestFiles

First we check any file existing nor not before delete them, will generate a vbDirectory according to file pattern, then go through one by one until hit first file, return True.

Private Function TestFiles(FilePattern, pFolder)

TestFiles = False

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

Dim strFile As String

strFile = Dir(pFolder & FilePattern, vbDirectory)
'MsgBox strFile
'MsgBox pFolder & strFile

Do While strFile <> ""

If fso.FileExists(pFolder & strFile) Then
    'MsgBox "Found file:" & pFolder & strFile
    TestFiles = True
    Exit Function
End If
strFile = Dir

Loop

Set fso = Nothing
End Function

script to delete number of files under one folder

Private Sub DeleteFiles(FilePattern, pFolder)

Set fso = CreateObject("Scripting.FileSystemObject")
'MsgBox pFolder & FilePattern
'Delete the files
If TestFiles(FilePattern, pFolder) Then
    fso.DeleteFile pFolder & FilePattern, True
Else
    'MsgBox pFolder & FilePattern & " not existing!"
End If

Set fso = Nothing

End Sub

test sample

This is test sample to delete all files under c:\test\

Private Sub delfilestest()
DeleteFiles "*", "c:\test\"
End Sub