Deleting Files the Kill Statement

You already know from one of the earlier sections that you can't delete a folder if it still contains files. To delete the files from any folder, use the following Kill statement:

Kill Pathname

Pathname specifies the names of one or more files that you want to delete. Optionally, Pathname may include the drive and folder name where the file resides. To enable quick deletion of files, you can use the wildcard characters (* or ?) in the Pathname argument. You can't delete a file that is open.

If you worked through the exercises in the preceding section, your hard drive now contains the folder C:\Abort with several files. In the following exercises, you'll first delete all the files from the Abort folder and then delete the folder itself:

1. Insert a new module into the current project and rename it KillStatement.

2. Enter the code of the RemoveMe procedure, as shown below:

Sub RemoveMe()

Dim folder As String Dim myFile As String

'assign the name of folder to the folder variable 'notice the ending backslash folder = "C:\Abort\" myFile = Dir(folder, vbNormal) Do While myFile <> "" Kill folder & myFile myFile = Dir

Loop

RmDir folder End Sub

3. Run the RemoveMe procedure. When the procedure ends, check Windows Explorer to see if the folder was removed.

0 0

Post a comment