1

I have a Sub in VBA (on a Mac) to delete a file, and it works correctly when the file exists. However, I get "Run-time error '53' File not found" when the file doesn't exist, even though the code is checking if it exists.

I tried a couple of different subs including from http://word.mvps.org/faqs/macrosvba/DeleteFiles.htm and Deleting a file in VBA

Sub DeleteFile()

Dim KillFile As String
KillFile = "/Users/me/Downloads/myfile.csv"
'Check that file exists
If Len(Dir$(KillFile)) > 0 Then
    'First remove readonly attribute, if set
    SetAttr KillFile, vbNormal
    'Then delete the file
    Kill KillFile
Else
End If

End Sub

Why am I getting this error when it should already be handled by the If statement?

Thanks.

EDIT: I want to delete/search for only this specific file, can I do that with Dir and MacID? I don't need to comb the directory for all CSV or TEXT files.

Community
  • 1
  • 1
lawtli23
  • 11
  • 4
  • I have never heard of `Dir$()` function? Is this a regular variation of `Dir()`? I would venture that that is the nature of your issue. – nbayly Oct 05 '16 at 17:23
  • I can't reproduce your error on my computer. When you step through the macro with F8, with a non-existing file, does it loop through your `If` statement, or skip it? It skips it for me. – BruceWayne Oct 05 '16 at 17:24
  • Getting the same error if I remove the $. @BruceWayne when I step through it, it highlights the If statement with no error, then at the next step, it highlights the If statement with an error. – lawtli23 Oct 05 '16 at 17:41
  • 1
    Is that your actuql path? houldnt it be more like C:\Users ? – Preston Oct 05 '16 at 17:42
  • What's the path, are you on Windows? Replace it with `"C:\Users\me\Downloads\myfile.csv"`. And I'm assuming `myfile.csv` does *not* exist anywhere in that folder. – BruceWayne Oct 05 '16 at 17:43
  • I'm on a Mac, path is the same with username and filename changed. It works when that file does exist in the folder. – lawtli23 Oct 05 '16 at 17:45
  • 1
    @nbayly - See [this example](http://stackoverflow.com/documentation/vba/877/declaring-variables/2960/type-hints#t=201610051751594390861) on Documentation. – Comintern Oct 05 '16 at 17:52
  • @Comintern see my edit - I couldn't get it to work using Dir() and MacID – lawtli23 Oct 05 '16 at 19:32

0 Answers0