title: Permission sometimes denied to kill/delete file
body: <p>I have an Excel program that relies on reading, appending, and creating text files.</p>
  
  <p>Since starting this project, once every 10-100 times, I get a</p>
  
  <blockquote>
    <p>"Run-time error '70': Permission denied"</p>
  </blockquote>
  
  <p>error when trying to kill/delete a text file.</p>
  
  <p>If I continue executing the code, it works.</p>
  
  <p>I've done some research about the error code, but that hasn't been much help.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>Close textfileorg
  Close textfileNew
      'Erstatter gammelt reg med nytt reg
  Do While isFileOpen(filepathorg): Loop
  Kill filepathorg
  Do While dir(filepathorg) &lt;&gt; "": Loop
  
  Do While isFileOpen(filepath): Loop
  Kill filepath
  Do While dir(filepath) &lt;&gt; "": Loop
  
  Name filepathNew As filepathorg
  </code></pre>
  
  <p>Here's my "is file open" check:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I suppose the problem could be avoided by using code along the lines of</p>
  
  <pre><code>failToKillFile:
      application.wait(time)
      resume
  </code></pre>
  
  <p>I feel that's just avoiding the problem. I would like to know why the error happens in the first place.</p>
  
  <p><strong>Edit</strong>: 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.</p>