Search code examples
vbaexceldir

excel 2010 vba, path/file access error


In the below excel 2010 vba if the answer the the prompt is no then the files in te folder, then the folder are deleted. However, I am getting a path/file access error when I run the vba. Specifically the RmDir MyFolder line is highlighted, but when I step-through the code the correct directory appears in the variable MyFolder and I can write new files to the directory. What am I missing? Thank you :).

Also, if I manually navigate to the directory, I can remove it.

iYesNo = MsgBox("Do the patients and barcode match the setup sheet?", vbYesNoCancel)
      Select Case iYesNo
             Case vbYes
             GoTo Line2
             Case vbNo
             MsgBox ("Doesn't match! Please enter again")
             MyFolder = Directory ' delete all txt files in the folder
             MyFile = Dir(MyFolder & "*.*")
             Do Until MyFile = ""
             Kill MyFile
             MyFile = Dir
             Loop

               RmDir MyFolder  ' delete folder
             GoTo Line1
       End Select

Solution

  • You most probably have a / at the end that prevent you from deleting the folder, see the correction.

    Also, you can change the Dir(...) to only select txt files to avoid deleting the rest of the files!

    Here is the code :

    iYesNo = MsgBox("Do the patients and barcode match the setup sheet?", vbYesNoCancel)
    Select Case iYesNo
        Case vbYes
            GoTo Line2
        Case vbNo
            MsgBox ("Doesn't match! Please enter again")
            MyFolder = Directory ' delete all txt files in the folder
            MyFile = Dir(MyFolder & "*.txt")
            Do Until MyFile = ""
                Kill MyFile
                MyFile = Dir
            Loop
    
            RmDir Left(MyFolder, Len(MyFolder) - 1) ' delete folder
            GoTo Line1
    End Select