VBA VB6 - When the test DIR (directory) goes down

October 2016

The simplest test to check out if the path of a directory is valid is of course ...

 If Dir (mydirectory) = "" Then 
        'The directory does not exist or is not well drafted 
    End If 

Exception ... If the directory path is correctly stared but empty ", but sometimes it may be necessary to determine if a directory exists, even if it is empty.
In such circumstances this test (courrtesy of lermite222)..may be useful

In a general module

Public Function TestSiVide(Rep As String) As Long 
Dim Obj, RepP, F 
    On Error GoTo Error 'If directory is not found 
    Set Obj = CreateObject("Scripting.FileSystemObject") 
    Set RepP = Obj.Getfolder(Rep) 
    Set F = RepP.Files 
    TestSiVide = F.Count 
    Set RepP = Nothing 
    Set F = Nothing 
    Set Obj = Nothing 
    Exit Function 
    TestSiVide = -1 
    Resume Output 'The Resume is necessary to avoid issues in the stack. 
End Function

And in the body of the code ...

Sub Test(Rep as String) 
Dim Nb As Long, MyDirectory as String 
    If Rep <> "" Then 
        MyDirectory = Rep & IIf(Right(Rep, 1) <> "\", "\", "")  
        Nb = TestSiVide(MonRepertoir ) 'Return -1 if error directory (error 76) 
        If Nb = 0 Then 
            MsgBox "The directory selected does not contain a file", vbCritical, "Select directory" 
        ElseIf Nb = -1 Then 
            MsgBox "The selected directory is not/ no longer valid", vbCritical, "Select directory" 
             MsgBox "The selected directory is valid" 
        End If 
    End If 
End Sub

Related :

This document entitled « VBA VB6 - When the test DIR (directory) goes down » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.