Friday, 3 July 2009

Use VBA to delete a file

This morning's annoyance was with Excel 2007. Somehow I'd created a file in the XLSTART folder (surprising as it's on a business drive to which I don't have access). To those of you that don't know, anything in this folder will be opened when excel starts.

So, my dilemma is this: How do I delete a file when I don't have access to it through Windows Explorer?

As I was in excel that got me into this mess, I figured it should be used to get out. A quick google revealed how to determine the name and path of the file I had open (link) and then how to perform basic file functions using VBA (link).

From that I put together a quick VBA macro to delete the file. I added a few message boxes along the way to check the path and then to give me the option to back out if I got cold feet at the last minute.

User names have been changed to protect the innocent.

Sub DeleteDefaultFile()

Dim Answer As String

MsgBox "Currently in " & CurDir
ChDir "C:\Users\######\AppData\Roaming\Microsoft\Excel\XLSTART\"
MsgBox "Now in " & CurDir

If Dir("C:\Users\######\AppData\Roaming\Microsoft\Excel\XLSTART\Sheet1.xls") <> "" Then
Answer = MsgBox("Delete the file?", vbYesNo)
Select Case Answer
Case vbYes
Kill "Sheet1.xls"
Case vbNo
MsgBox "User Aborted"
Exit Sub
End Select
Else: MsgBox "The file does not exist", vbOKOnly + vbExclamation
End If

End Sub

For some reason, inlining didn't copy to the blogger so it's all flat, even if I manually put the spaces in. Sorry.

No comments:

Post a Comment