Delete all files in folder Except one

alsharif

New Member
Joined
Mar 14, 2021
Messages
14
Office Version
  1. 2019
Platform
  1. Windows
Greetings,

Seeking your help for VBA code that I can use to delete all files from different types in folder path " C:\Users\alshas\Desktop\Archive" and keep only one file which is named "Final.xlsx"

Thank you in advance
 
See if the following code works for you:
VBA Code:
Sub DelButOne()
    Dim PName As String, FName As String
    PName = "C:\Users\alshas\Desktop\Archive"
    FName = "Final.xlsx"
    Shell "cmd /C cd """ & PName & """ && attrib -A *.* && attrib +A """ & FName & """ && del /Q /F /A:-A *.*"
End Sub
Caution: Please test it on a non-critical folder.
 
Upvote 0
Try . . .

VBA Code:
Option Explicit

Sub DeleteAllFilesExceptOne()

    Dim path As String
    path = "C:\Users\alshas\Desktop\Archive\"
    If Right(path, 1) <> "\" Then
        path = path & "\"
    End If
    
    Dim exceptedFile As String
    exceptedFile = "Final.xlsx"
    
    Dim currentFile As String
    currentFile = Dir(path & "*.*", vbNormal)
    
    While (Len(currentFile) > 0)
        If LCase(currentFile) <> LCase(exceptedFile) Then
            Kill path & currentFile
        End If
        currentFile = Dir
    Wend
    
    MsgBox "Completed!", vbExclamation
    
End Sub

Hope this helps!
 
Upvote 0
... it did not work.
First of all, this ^^^ is not particularly helpful for troubleshooting.

Second of all, the code offered in Post #2 has been tested to work under Win 7 / Excel 2010 and under Win 10 / Excel 365.
 
Upvote 0

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