Search code examples
vbanetwork-programmingdelete-file

Verify files not in use before attempting to delete a folder on the network


Set fso = CreateObject("Scripting.FileSystemObject")
BazKlasor = "\\SRV01\l.urge\01 IS TAKIP\11 BAZ"
ArsivKlasor = "\\SRV01\l.urge\80 ARSIV\01 IS TAKIP\11 BAZ"

arsiveGonKlasor = BazKlasor & "\" & Me.FR15_cmb01.Value

If fso.folderexists(arsiveGonKlasor) Then
   fso.CopyFolder arsiveGonKlasor, ArsivKlasor & "\"
   fso.deletefolder arsiveGonKlasor
Else
   MsgBox Me.FR15_cmb01.Value & " KLASÖRÜ BULUNAMADI. İŞLEM SONLANDIRILIYOR", vbCritical, "L.URGE"
   Call sifrekapat
   Exit Sub
End If

I can delete a folder on the network with the code above.

If someone is working on the files in the folder, I get an error. How can I check this before I start deleting?


Solution

  • Instead of trying to check whether someone is using a file in the folder, it would be simpler to use error handling to attempt deletion of the folder, catching the error and doing something useful if it fails. For example:

       On Error GoTo ErrorHandler   ' Enable error-handling routine.
    
       Set fso = CreateObject("Scripting.FileSystemObject")
       BazKlasor = "\\SRV01\l.urge\01 IS TAKIP\11 BAZ"
       ArsivKlasor = "\\SRV01\l.urge\80 ARSIV\01 IS TAKIP\11 BAZ"
    
       arsiveGonKlasor = BazKlasor & "\" & Me.FR15_cmb01.Value
    
       If fso.folderexists(arsiveGonKlasor) Then
          fso.CopyFolder arsiveGonKlasor, ArsivKlasor & "\"
          fso.deletefolder arsiveGonKlasor
       Else
          MsgBox Me.FR15_cmb01.Value & " KLASÖRÜ BULUNAMADI. İŞLEM SONLANDIRILIYOR", vbCritical, "L.URGE"
          Call sifrekapat
          Exit Sub
       End If
    
       MsgBox "Delete worked!"
    
       Exit Sub
    
    ErrorHandler:    ' Error-handling routine.
       MsgBox "Delete failed! Error: " & Err.Number & " : " & Err.Description
    
       'Do something useful here