Link to home
Start Free TrialLog in
Avatar of srejja
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
Avatar of jppinto
jppinto
Flag of Portugal image

See if you can adapt the code from this post:

http://excel-user.blogspot.com/2009/10/replace-value-on-several-excel-files.html

jppinto
Avatar of srejja
srejja

ASKER

No success with that one.  I am a mere apprentice VBA coder :(
ASKER CERTIFIED SOLUTION
Avatar of Dave
Dave
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of srejja

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))


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