Log in

View Full Version : [SOLVED:] Kill Files that Begin With Something



aerodoc
03-15-2014, 03:31 PM
I want to delete files (I guess using Kill), but only files that begin with a given string. In other words "del string*.*" It has to work for Excel 2003 and later. Thanks.

ashleyuk1984
03-15-2014, 04:08 PM
Here you go, this works for me in Excel 2010. I have no idea if this will work in 2003?? You'll just have to try it.


Sub DeleteFilesBeginningWith()

'Enable Macro to view system files (folders and files)
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

'Tell Macro which folder to work with
Set FolderObj = FileSystemObj.GetFolder("C:\TestFolder\") '<------ CHANGE THIS

'Create a FOR loop to look at each file within the folder and search for certain criteria
For Each FileObj In FolderObj.Files

'In this case the criteria is to search the first four characters of each file. If a file is found to have "test" as the first four characters perform the next task.
If Left(FileSystemObj.GetFileName(FileObj.Path), 4) = "test" Then '<------ CHANGE THIS

'The next task is to DELETE the file
Kill FileObj

End If

'Jump to next file in the directory, and repeat loop. This will keep repeating until all files have been looked at.
Next FileObj

End Sub

westconn1
03-15-2014, 04:28 PM
what is wrong with

kill "c:\somepath\" & string & "*.*"


In Microsoft Windows, Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files. However, on the Macintosh, these characters are treated as valid file name characters and can't be used as wildcards to specify multiple files.

ashleyuk1984
03-15-2014, 04:40 PM
Yup that works perfectly fine too lol.


Sub DeleteFiles()


Kill "C:\TestFolder\" & "test" & "*.*"


End Sub

aerodoc
03-18-2014, 08:35 PM
Thanks,

This small variation worked in my case

Kill "C:\TestFolder\" & "test" & ".*"

snb
03-19-2014, 02:37 AM
so why not ?


Kill "C:\TestFolder\test.*"

aerodoc
03-19-2014, 06:13 PM
That would work too, but in my case the directory is a variable so I used
Kill Cells(1,1) & "test" & ".*", but is probably better done as
Kill Cells(1,1) & "test.*"

snb
03-20-2014, 01:53 AM
I agree.