none
How do I delete all files in a folder? RRS feed

  • Question

  • Hi,

    Why will this code not delete any files in the folder?

    The folder contains .xls and .zip files.

    Kill "C:\Users\myname\Desktop\Mail Extract\*.*"

    If I use Kill "C:\Users\myname\Desktop\Mail Extract\*.zip*" it does delete the Zip files.

    But Kill "C:\Users\myname\Desktop\Mail Extract\*.xls*" does not delete the Excel files.

    Can anyone please help me?

    Wednesday, October 14, 2015 11:08 AM

All replies

  • All three of your examples work for me, as does simply <folder>\"*"

    Is the workbook you are running your code from in the same folder?

    Wednesday, October 14, 2015 11:35 AM
    Moderator
  • Hi Peter,

    Strange.

    My workbook is in a different folder to where I deleting the files from.

    Wednesday, October 14, 2015 1:05 PM
  • You can use use FileSystemObject (FSO).  Here is a good reference:

    FileSystemObject

    Here is something that should work

    Sub test()
      Dim fso As New FileSystemObject
      
      fso.DeleteFolder ("C:\Users\myname\Desktop\Mail Extract")
      fso.CreateFolder ("C:\Users\myname\Desktop\Mail Extract")
    End Sub
    There are other ways to do it using FSO.  If it doesn't work you may have a lock on some zip file.


    • Proposed as answer by André Santo Wednesday, October 14, 2015 1:56 PM
    • Edited by mogulman52 Wednesday, October 14, 2015 8:59 PM
    Wednesday, October 14, 2015 1:43 PM
  • Please see the link below.

    http://www.rondebruin.nl/win/s4/win004.htm


    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Wednesday, October 14, 2015 9:52 PM
  • Thanks for the reply.

    The rondebruin example is exactly what I have done, but doesn't work for me.

    Thursday, October 15, 2015 1:58 PM
  • Hummm, I've used it many times.  It has never NOT worked fro me.  Do you have those files open?  You can't delete a file if it's open.  Also, the Name property is just the file name.  The Kill method requires the full path.  Try using the FullName propertyand see if that works.  It should definitely work.

    If all else fails, reboot your machine.  You may have a reference to a file that you are trying to delete.  That essentially means the file is in use, and thus it can't be deleted. 


    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Thursday, October 15, 2015 2:13 PM
  • You can use this command as alternative to fso:

    VBA.Kill sPath_or_PathAndFile

    If is opened, you should close application using TerminateProcess


    Oskar Shon, Office System MVP - www.VBATools.pl
    if Helpful; Answer when a problem solved

    Friday, October 23, 2015 11:04 PM
    Answerer