Consulting

Results 1 to 8 of 8

Thread: Kill Files that Begin With Something

  1. #1
    VBAX Regular
    Joined
    Oct 2010
    Posts
    85
    Location

    Kill Files that Begin With Something

    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.

  2. #2
    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

  3. #3
    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.

  4. #4
    Yup that works perfectly fine too lol.

    Sub DeleteFiles()
    
    
    Kill "C:\TestFolder\" & "test" & "*.*"
    
    
    End Sub

  5. #5
    VBAX Regular
    Joined
    Oct 2010
    Posts
    85
    Location
    Thanks,

    This small variation worked in my case
    Kill "C:\TestFolder\" & "test" & ".*"

  6. #6
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,645
    so why not ?

    Kill "C:\TestFolder\test.*"

  7. #7
    VBAX Regular
    Joined
    Oct 2010
    Posts
    85
    Location
    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.*"

  8. #8
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,645
    I agree.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •