meer2kat
meer2kat

Reputation: 241

Why can't I delete this folder (VBA)?

I created a temporary folder that gets deleted later on in the program using this code:

    'Creates a new temporary      directory path for a folder copy
    If dir("C:\\InventorTempFolder\\\", vbDirectory) = "" Then       
MkDir "C:\\InventorTempFolder\\\"
SetAttr "C:\InventorTempFolder", vbNormal
    Else: MsgBox "This folder already exists."
    End If


(I don't know if the SetAttr is right...that's part of my question!)

I then pulled this code offline that should delete all the files and directories in this folder, using this code:

Sub DeleteDirectory()


Dim dir_name As String
Dim file_name As String
Dim files As Collection
Dim i As Integer
dir_name = "C:\\InventorTempFolder"

' Get a list of files it contains.
Set files = New Collection
file_name = dir$(dir_name & "\*.*", vbReadOnly + _
    vbHidden + vbSystem + vbDirectory)
Do While Len(file_name) > 0
    If (file_name <> "..") And (file_name <> ".") Then
        files.Add dir_name & "\" & file_name
    End If
    file_name = dir$()
Loop

' Delete the files.
For i = 1 To files.Count
    file_name = files(i)
    ' See if it is a directory.
If GetAttr(file_name) = vbDirectory Then
        Kill file_name
Else: Kill file_name
End If

Next i

' The directory is now empty. Delete it.
RmDir dir_name

' Remove the read-only flag if set.
' (Thanks to Ralf Wolter.)

End Sub


However, the directory won't delete. My theory is that it is because the directory is a read-only folder. That is why I tried to change the attribute to vbNormal, but it won't change. So questions I'm wondering is:

  1. Why won't it delete? Is my theory right that it is because it is read-only?

  2. If so, how can I fix that?

  3. If not, what else is wrong...?


Thanks ahead of time!

Upvotes: 0

Views: 5262

Answers (1)

Joe
Joe

Reputation: 6827

The end of your script is:

RmDir dir_name

' Remove the read-only flag if set.
' (Thanks to Ralf Wolter.)

RmDir dir_name

So you're attempting to remove the same directory twice. And dir_name at this point is set to the "SillyVBA" directory -- this did get deleted when I tested it. I'm assuming the second RmDir is meant to delete "C:\InventorTempFolder"; that also worked for me when I tested it.

Updated in response to comment

The problem is likely due to your attempt to use Kill when the file type is a directory. To do a full recursive delete, you would need to start at the bottom of the tree, deleting all files and empty directories as you work your way up. However a much easier way is to use FileSystemObject:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.deletefolder dir_name

This will delete the directory and everything in it, in one shot.

Upvotes: 2

Related Questions