Delete all files in a folder - 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,

A more simple way:
Sub Del()
Kill "C:\FolderName\*.*"
End Sub

Add a reference to Microsoft Scripting Runtime in the VBA environment
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

You should not name macros as the in built functions. Just changing the macros with the same coding resolves the issues...
Sub Kill1 ()
Dim aFile As String
aFile = "C:\Test\Test\Downloads\*.*"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
End Sub

Related

Creating Specific Folders

I'm using these two functions to create project folders on startup. In the beginning I'm creating only one folder named ProjectName but now there's other folders on the same level with ProjectName named ProjectName_Inputs, ProjectName_Files, ProjectName_Outputs. I want to create them with my below code.
I wonder how can I adapt this to my code. I mean, is it possible to use an array or for loop etc.? path = [/ProjectName, ProjectName_Inputs, ProjectName_Files, ProjectName_Outputs] I don't know if it's possible?
Or can you suggest a more logical way to create them?
Sub CreateFolders()
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Sub
Else
On Error GoTo FolderNotBuilt
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Sub
End If
FolderNotBuilt:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Sub
End Sub
This is the function that controls whether or not the directory created before
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExists = True
End Function
Edited to amend a typo (End With missing) and change Resume to Resume Nextand skip the possibly screwed up path
I’d go like follows
Sub CreateFolders()
Dim path As Variant
With CreateObject("Scripting.FileSystemObject") 'create and reference a FileSystemObject object
For Each path In Array("path1*\", "path2", "path3")
If Not .FolderExists(path) Then 'loop through paths in array
On Error GoTo FolderNotBuilt
.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
End If
Next
End With
Exit Sub
FolderNotBuilt:
MsgBox "A folder could not be created for the following path: " & vbCrLf & vbCrLf & path & vbCrLf & "Check the path name and try again."
Resume Next
End Sub

vba Bad file name or number

I have problem. This is a code
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If FolderExist(path) Then
Exit Function
Else
fso.CreateFolder path
Exit Function
End If
End Function
Function FolderExist(ByVal path As String) As Boolean
FolderExist = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExist = True
End Function
i try too create folder U:\Paweł\Generator\Akus Marcin 20180108001
and i get a bad file name or number.
when i try to create other folder like this U:\Paweł\Generator\Bedrunka Brunon 20171219001 there is no problem. What's wrong with the name of the folder?
thanks for the answer
Not an answer to the question, but possibly a solution to the problem, with code using MkDir that has been tested and acknowledged by others.
Function FolderCreate(ByVal path As String) As Boolean
'Dim strDir As String
'strDir = "C:\My Documents\TestDir\"
If Dir(path, vbDirectory) = "" Then
MkDir path
FolderCreate = True
Else
MsgBox "Directory exists."
FolderCreate = False
End If
End Function
From your code it is not clear if you want the assignments of the return value as I used, the opposite, or something else.
You may modify this.
Source: adapted from http://www.vbaexpress.com/forum/showthread.php?7866-Check-for-folder-create-if-it-does-not-exist
You may also try other tested code, or take snippets from there...
https://www.extendoffice.com/documents/excel/4182-excel-check-if-folder-exists.html
This worked with the folders I created. No references need to be set as it's using Late Binding.
Sub Test()
CreateFolder "U:\Pawel\Generator\Akus Marcin 20180108001"
CreateFolder "U:\Pawel\Generator\Bedrunka Brunon 20171219001"
End Sub
Sub CreateFolder(Folder As String)
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
With oFSO
If Not .FolderExists(Folder) Then
.CreateFolder Folder
End If
End With
End Sub
Edit: Testing with your code didn't return any errors either. If my code returns errors it may be a system setting that's stopping the folder being created (but that doesn't explain why one folder gets created while the other doesn't in the same parent folder).

VBA Verify File extension as excel file?

I run this vba which goes through folders and pulls data which it compiles together in one big sheet. My issue is I was getting errors for hidden files called thumbs.db and I need to add something so that it verifies that it is only pulling files with xlsx extensions. Below is the code I am using.
Sub DoFolder(Folder)
Dim SubFolder As Folder
Dim i As Integer
Dim CopyR As Range
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
If Folder.SubFolders.Count = 0 Then
If Folder.Files.Count = 1 Then
If Mid(Folder.Files, Len(Folder.Files) - 3, 4) = "xlsx" Then
Else: MsgBox "2+ files: " & Folder.Path
End If
End If
For Each File In Folder.Files
Hoover File
Next
Else
End If
End Sub
The line I am having issues with figuring out is
If Mid(Folder.Files, Len(Folder.Files) - 3, 4) = "xlsx" Then
Any help on this would be really appreciated
Folder.Files is a collection not a string.
Recursive File Search:
Sub DoFolder(FolderName As String, Optional fso As Object)
Dim f As Object, MySubFolder As Object, RootFolder As Object
Dim cFiles As Collection
If fso Is Nothing Then Set fso = CreateObject("Scripting.FileSystemObject")
Set RootFolder = fso.GetFolder(FolderName)
For Each MySubFolder In RootFolder.SubFolders
DoFolder MySubFolder.Path, fso
Next
Set cFiles = New Collection
For Each f In RootFolder.Files
If f.Name Like "*xls*" Then cFiles.Add f
Next
If cFiles.Count > 0 Then
MsgBox cFiles.Count & " files found in " & RootFolder.Name
For Each f In cFiles
Hoover f
Next
End If
End Sub
A quick solution is simply to check for xlsx being contained in the name of the file. Like this:
If InStr(1,"FileName","xlsx",vbTextCompare)<1 then
Thus, you would be in the safe side, unless someone renames thumbs.db to thumbsxlsx.db.
Assuming you're using the FileSystemObject, which it looks like you are even though we can't see the declarations, and assuming you're only wanting to call Hoover for .xlsx files you can use the following code
If Right(File.Name, 4) = "xlsx" Then
Hoover File
End If
As a further improvement to the answer by user6432984.. FSO does have a function to obtain the file extension, but the function is not part of the File object, but is the fso.GetExtensionName()
You would expect that the File.Type property could be used, but that gives the application name associated with that file extension - not very useful.
If f.Type Like "*xls*" Then cFiles.Add f
However the FSO-based function works as follows:
For Each f In RootFolder.Files
If fso.GetExtensionName(f.Path) Like "*xls*" Then cFiles.Add f
Next

FileSystemObject.CreateFolder to create directory and subdirectories

I would like to create a directory and a subdirectory with the following code:
Public fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
fso.CreateFolder ("C:\Users\<my_username>\DataEntry\logs")
I am trying to create nested directories. In this case, the DataEntry directory would not exist, so essentially I would like to create 2 directories, DataEntry\logs under C:\Users\<username>
If I enter command prompt, I can create that directory with mkdir without any issues. However, I simply cannot get VBA to create that folder and I get:
Run-time error '76':
Path not found
I am using Excel VBA 2007/2010
tigeravatar's looping answer might work, but it's a bit hard to read. Instead of micromanaging the string handling yourself, the FileSystemObject has path manipulation functions available, and recursion is slightly easier to read than a loop.
Here is the function I use:
Function CreateFolderRecursive(path As String) As Boolean
Dim FSO As New FileSystemObject
'If the path exists as a file, the function fails.
If FSO.FileExists(path) Then
CreateFolderRecursive = False
Exit Function
End If
'If the path already exists as a folder, don't do anything and return success.
If FSO.FolderExists(path) Then
CreateFolderRecursive = True
Exit Function
End If
'recursively create the parent folder, then if successful create the top folder.
If CreateFolderRecursive(FSO.GetParentFolderName(path)) Then
If FSO.CreateFolder(path) Is Nothing Then
CreateFolderRecursive = False
Else
CreateFolderRecursive = True
End If
Else
CreateFolderRecursive = False
End If
End Function
Need to create each folder one at a time. You can use code like this to do so:
Sub tgr()
Dim strFolderPath As String
Dim strBuildPath As String
Dim varFolder As Variant
strFolderPath = "C:\Users\<my_username>\DataEntry\logs"
If Right(strFolderPath, 1) = "\" Then strFolderPath = Left(strFolderPath, Len(strFolderPath) - 1)
For Each varFolder In Split(strFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Agree with MarkD's suggestion to utilize recursion, it was the code I came here looking to find. In a scenario where the path provided uses a nonexistent root folder it will result in an infinite loop. Adding to MarkD's solution to check for zero length path.
Function CreateFolderRecursive(path As String) As Boolean
Static FSO As FileSystemObject
'Initialize FSO variable if not already setup
If FSO Is Nothing Then Set lFSO = New FileSystemObject
'Is the path paramater populated
If Len(path) = 0 Then
CreateFolderRecursive = False
Exit Function
End If
'If the path exists as a file, the function fails.
If FSO.FileExists(path) Then
CreateFolderRecursive = False
Exit Function
End If
'If the path already exists as a folder, don't do anything and return success.
If FSO.FolderExists(path) Then
CreateFolderRecursive = True
Exit Function
End If
'recursively create the parent folder, then if successful create the top folder.
If CreateFolderRecursive(FSO.GetParentFolderName(path)) Then
If FSO.CreateFolder(path) Is Nothing Then
CreateFolderRecursive = False
Else
CreateFolderRecursive = True
End If
Else
CreateFolderRecursive = False
End If
End Function

Open an external EXE. file using VBA Powerpoint

Please help me make this code works. I want to open an external EXE file using Powerpoint VBA.
Sub open_test()
Dim FileName, FSO, MyFile
FileName = "C:\test.exe"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
End Sub
There are no compiler errors, but when i execute the macro, it does nothing ... I have another alternatives to this code? please help me, thanks!
If you just want to start the program, try using
Sub open_test()
Dim sFullPathToExecutable as String
sFullPathToExecutable = "C:\test.exe"
Shell sFullPathToExecutable
End Sub