Excel VBA - Delete any and all .csv files in the same folder

TropicalMagic

New Member
Joined
Jun 19, 2021
Messages
47
Office Version
  1. 365
Platform
  1. Windows
Hi, I would like to delete any and all .csv files in the same folder.

However, the code isn't working as there is a run-time error 53: "File not found" at the "Kill ThisFile" line.


VBA Code:
Sub Delete_CSV_Files()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim MyFolderPath As String
Dim ThisFile As Variant

MyFolderPath = Application.DefaultFilePath
ThisFile = MyFolderPath & Dir(MyFolderPath & "\" & "*.csv", vbNormal)

While ThisFile <> ""
Kill ThisFile
ThisFile = MyFolderPath & Dir
Wend

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub


Can anyone help me with the issue?

Many thanks!
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
VBA Code:
Sub KillThisFile()

Dim ThisFile  As String
Dim MyFolderPath As String

MyFolderPath = Application.ActiveWorkbook.Path
ThisFile = MyFolderPath & "\" & "*.csv"

If Len(Dir$(ThisFile)) > 0 Then
    Kill ThisFile
End If

End Sub
 
Upvote 0
Solution
VBA Code:
Sub KillThisFile()

Dim ThisFile  As String
Dim MyFolderPath As String

MyFolderPath = Application.ActiveWorkbook.Path
ThisFile = MyFolderPath & "\" & "*.csv"

If Len(Dir$(ThisFile)) > 0 Then
    Kill ThisFile
End If

End Sub

Fantastic, many thanks! It was what i was looking for!

I made a minor adjustment:

VBA Code:
Sub KillThisFile()

Dim ThisFile  As String
Dim MyFolderPath As String

MyFolderPath = Application.DefaultFilePath
ThisFile = MyFolderPath & "\" & "*.csv"

If Len(Dir$(ThisFile)) > 0 Then
    Kill ThisFile
End If

End Sub
 
Upvote 0

Forum statistics

Threads
1,213,537
Messages
6,114,216
Members
448,554
Latest member
Gleisner2

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top