srejja
asked on
VBA to delete all files in folder whose name begin with specific striing
I need code that will delete all files within a folder that begin with a specific string, except for the most recent version.
For instance in folder C:\ I will have the following files:
C:\Test_01292010.zip
C:\Test_01282010.zip
C:\Test_01272010.zip
C:\Test_01262010.zip
C:\KeepMe_01252010.zip
C:\SaveMe_01282010.xls
In this example only files I would want anything beginning with "Test_" deleted except for the most recent version " C:\Test_01292010.zip". Thus C:\Test_01282010.zip, C:\Test_01272010.zip, C:\Test_01262010.zip would be deleted and the rest would be kept. How would I go about achieving this?
Thus far I've been using the code below to delete specific files.
Public Sub KillProperly(Killfile As String)
On Error Resume Next
If Len(Dir$(Killfile)) > 0 Then
SetAttr Killfile, vbNormal
Kill Killfile
End If
End Sub
Now
For instance in folder C:\ I will have the following files:
C:\Test_01292010.zip
C:\Test_01282010.zip
C:\Test_01272010.zip
C:\Test_01262010.zip
C:\KeepMe_01252010.zip
C:\SaveMe_01282010.xls
In this example only files I would want anything beginning with "Test_" deleted except for the most recent version " C:\Test_01292010.zip". Thus C:\Test_01282010.zip, C:\Test_01272010.zip, C:\Test_01262010.zip would be deleted and the rest would be kept. How would I go about achieving this?
Thus far I've been using the code below to delete specific files.
Public Sub KillProperly(Killfile As String)
On Error Resume Next
If Len(Dir$(Killfile)) > 0 Then
SetAttr Killfile, vbNormal
Kill Killfile
End If
End Sub
Now
ASKER
No success with that one. I am a mere apprentice VBA coder :(
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks Brett. I tried your code and received an error: Run-time error '13': Type mismatch
When debugging this line of code is highlighted:
ConDate = DateSerial(Right$(anyStr, 4), Left$(anyStr, 2), Mid$(anyStr, 3, 2))
When debugging this line of code is highlighted:
ConDate = DateSerial(Right$(anyStr, 4), Left$(anyStr, 2), Mid$(anyStr, 3, 2))
Do your file all have the layout like
XXX_mmddyyyy
as per your sample data?
as long as the "_" precedes an eight character date (as per your sample data) then the code should work
Cheers
Dave
XXX_mmddyyyy
as per your sample data?
as long as the "_" precedes an eight character date (as per your sample data) then the code should work
Cheers
Dave
http://excel-user.blogspot.com/2009/10/replace-value-on-several-excel-files.html
jppinto