Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files in a folder

Tags:

file

kill

vba

I have the below code to try search for all files in my downloads folder and then delete them all however it's returning an error message based on the kill function not having enough arguments, any ideas?

Sub Kill ()

Dim aFile As String
aFile = "C:\Test\Test\Downloads\*.*"
If Len(Dir$(aFile)) > 0 Then
    Kill aFile
End If

End Sub

Thanks,

like image 761
Brentford123 Avatar asked May 24 '17 15:05

Brentford123


2 Answers

A more simple way:

Sub Del()
  Kill "C:\FolderName\*.*"
End Sub
like image 157
Delmar Silva Avatar answered Oct 11 '22 13:10

Delmar Silva


Add a reference to Microsoft Scripting Runtime in the VBA environment

ref

scr

The declare in a Module the following line

Global fso As New FileSystemObject

Now you can use all the nice and modern I/O functions. For example:

Public Sub TDELFOL()    
    Dim path As String, f As File
    path = fso.GetSpecialFolder(TemporaryFolder)
    path = fso.BuildPath(path, "MyTempFolder")
    If fso.FolderExists(path) Then
        For Each f In fso.GetFolder(path).Files
            f.Delete Force = True
        Next
        fso.DeleteFolder path, Force = True
    End If
End Sub
like image 29
John Alexiou Avatar answered Oct 11 '22 13:10

John Alexiou