Permission sometimes denied to kill/delete file

Viewed 11798

I have an Excel program that relies on reading, appending, and creating text files.

Since starting this project, once every 10-100 times, I get a

"Run-time error '70': Permission denied"

error when trying to kill/delete a text file.

If I continue executing the code, it works.

I've done some research about the error code, but that hasn't been much help.

Earlier, I theorized the file doesn't get time to close, before Excel tries to kill it. I tried a function that waited for the file to be closed, so unless my code for that doesn't work, I don't think that's the problem.

Here's my code for closing and deleting files. Note, it's on the "Kill" command it stops. The "isFileOpen" and "dir" commands were to check if the error was due to 1) files not being closed yet, and 2) files not being deleted yet.

Close textfileorg
Close textfileNew
    'Erstatter gammelt reg med nytt reg
Do While isFileOpen(filepathorg): Loop
Kill filepathorg
Do While dir(filepathorg) <> "": Loop

Do While isFileOpen(filepath): Loop
Kill filepath
Do While dir(filepath) <> "": Loop

Name filepathNew As filepathorg

Here's my "is file open" check:

Function isFileOpen(ByRef filepath As String)

Dim textfile As Integer
textfile = FreeFile

On Error GoTo fileOpenErr

    'Forsøker å åpne fil
Open filepath For Random As textfile
Close textfile

    'Om ok, returner at fil ikke er åpen
isFileOpen = False

Exit Function

    'Ved error, returner at fil var åpen
fileOpenErr:
    isFileOpen = True

End Function

I suppose the problem could be avoided by using code along the lines of

failToKillFile:
    application.wait(time)
    resume

I feel that's just avoiding the problem. I would like to know why the error happens in the first place.

Edit: Just as I posted this, I got a similar error trying to copy a file, where the copy would have to replace a file. Press continue, and everything works.

3 Answers

I had this very issue and nothing seemed to solve it until i moved the kill command into a separate subroutine and called it from the main routine...in my case:

Sub KillWB()
Dim UPath As String, WB As String
UPath = "C:\Users\" & Environ("username")
WB = UPath & "\Temp.xlsx"
Kill WB
End Sub
Related