简体   繁体   中英

“Kill” / “FileCopy” leads to permission denied

I'm having a problem with my Access VBA macro which for some reason is breaking on those lines with error "Permission Denied [Run-time error 70]:

sOutputFile = CurrentProject.Path & "\Output Files\Recon\" & sDate & " " & sClient & " Cash Recon.xlsx"
sTemplateFile = CurrentProject.Path & "\Temp Files\Template_Listed.xlsx"
If Dir(sOutputFile) <> "" Then Kill sOutputFile
FileCopy sTemplateFile, sOutputFile

What's getting "pointed out" directly is the "Kill sOutputFile" phrase.

It is worth to mention, that I do not have any of the files open, I have full access to the directories, and not long ago (before declaring sOutputFile and sTemplateFile) they've been both cleared.

Any help is much appreciated and I'm willing to share more of my code if needed.

Edit: Also, from time to time, the macro goes to the next line and breaks at the FileCopy instead.

The logic is not quite right in my opinion, please try the following (FileCopy should be inside an If...End If):

sOutputFile = CurrentProject.Path & "\Output Files\Recon\" & sDate & " " & 
sClient & " Cash Recon.xlsx"
sTemplateFile = CurrentProject.Path & "\Temp Files\Template_Listed.xlsx"
If FileExists(sOutputFile) Then 
  Kill sOutputFile
  FileCopy sTemplateFile, sOutputFile
End If

And this is the FileExists function:

Public Function FileExists_1(sFileName As String) As Boolean
  Dim obj_fso As Object

  Set obj_fso = CreateObject("Scripting.FileSystemObject")
  FileExists_1 = obj_fso.fileExists(sFileName)

  Set obj_fso = Nothing
End Function

What was the issue in my case, was that I previously used the macro, but the full ran failed. After trying to run it again after few adjustments (not related to the code I posted here), the above issue was happening. All just because I had the file still open somewhere in my excel's memory, hence the file couldn't be deleted.

Thanks for all the contributions guys. You're amazing as always!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM