VB and VBA Users Source Code: Deleting all the files in a directory which match a pattern
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Deleting all the files in a directory which match a pattern
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, September 07, 2000
Hits:
732
Category:
Files/Directories/IO
Article:
To delete multiple files from a directory based on a string pattern eg. "C:\temp\*.tmp", use the following routines: 'Purpose : Delete single or multiple files, based on the specified pattern 'Inputs : sFilePattern The full path and name or file pattern (can include either * or $) ' [bDeleteReadOnly] If True, routine will delete readonly files 'Outputs : Returns zero on success, or a count of the files that could not be deleted. 'Author : Andrew Baker 'Date : 07/09/2000 'Notes : VBA.Kill will stop deleting and raise an error, as soon as it fails to delete a file. ' This routine will continue trying to delete any matching files.'Revisions : Function FileKillMatching(sFilePattern As String, Optional bDeleteReadOnly As Boolean) As Boolean Dim sThisFile As String, sThisPath As String Dim sFileDelete As String Dim lCountFailed As Long On Error GoTo ErrFailed If InStr(1, sFilePattern, "*") > 0 Or InStr(1, sFilePattern, "$") > 0 Then 'Kill multiple files sThisPath = PathFileToPath(sFilePattern) sThisFile = Dir(sFilePattern, vbNormal) Do While Len(sThisFile) If sThisFile <> "." And sThisFile <> ".." Then sFileDelete = sThisPath & sThisFile If bDeleteReadOnly Then SetAttr sFileDelete, vbNormal End If Kill sFileDelete End If sThisFile = Dir$ Loop Else If bDeleteReadOnly Then SetAttr sFilePattern, vbNormal End If Kill sFilePattern End If FileKillMatching = lCountFailed On Error GoTo 0 Exit Function ErrFailed: Debug.Print "Failed to delete " & sFileDelete & ". Error: " & Err.Description lCountFailed = lCountFailed + 1 Resume Next End Function 'Purpose : Strips off the file name from a string. 'Inputs : sPathFileName A path and file name 'Outputs : The path the file is stored in. ' eg. "C:\WinNT\System32\Xcopy.exe" returns "C:\WinNT\System32\" 'Author : Andrewb 'Date : 07/09/2000 'Notes : In VB/Excel 2000, alter function to use InStrRev for speed 'Revisions : Function PathFileToPath(sPathFileName As String) As String Dim lThisChar As Long For lThisChar = 0 To Len(sPathFileName) - 1 If Mid$(sPathFileName, Len(sPathFileName) - lThisChar, 1) = "\" Then PathFileToPath = Left$(sPathFileName, Len(sPathFileName) - lThisChar) Exit For End If Next End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder