Delete Files from Access VBA

I need to create some vba code that will delete all files in a specific folder. But I need it to only delete the files that end in 2 specific characters. For example I need it to delete all the PDF files that end in "RM". I know to use the Kill function but not entirely sure how to write the code to specify the file names ending in "RM".
LVL 1
Lawrence SalvucciInformation Technology ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim Dettman (Microsoft MVP/ EE MVE)President / OwnerCommented:
Use the Dir() command with a path.

It will return a file name.   Inspect the file name with Left(), Mid(), InStr() etc to decide if you want to remove it.  If so, use Kill on it.

THen call Dir() again with no argument.   That will return the next file in the directory.   Do all this in a loop.  When Dir() returns no filename, you've inspected every file in the directory.

Jim.
Saurabh Singh TeotiaCommented:
You can use the following code to do what you are looking for...

Sub deletedata()
    Dim objFSO As Object
    Dim xpath As String
    Dim fname As String

    xpath = "Your path here"

    fname = Dir(xpath & "*.pdf")

    Set objFSO = CreateObject("scripting.filesystemobject")

    Do Until fname = ""

        If Trim(UCase(Right(fname, 6))) = "RM.PDF" Then objFSO.DeleteFile xpath & fname, True
        fname = Dir()

    Loop

End Sub

Open in new window


Saurabh...

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rgonzo1971Commented:
Hi,

to test if it ends with RM you could try
Filename = Dir("C:\")
If Split(Filename, ".")(0) Like "*RM" Then
    'End, with RM
End If

Open in new window

Regards
Lawrence SalvucciInformation Technology ManagerAuthor Commented:
Thank you for your quick responses!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.