Search code examples
excelfilesystemobjectfsovba

Unable to open file using fso


I'm trying to open a file using FileSystemObject, but when I'm trying to run it, the system does nothing. Doesn't show me Debug, No runtime error, doesn't compile. It just remains as it is. I have also checked the "MS Scripting Runtime" in References. Below is the code I've used for this:

Sub fsoobject()
Dim fso As New FileSystemObject, f As Folder, sf As Folder, myFile As File
Set f = fso.GetFolder("C:\Users\jpmehta\Desktop")

For Each sf In f.SubFolders
    For Each mySubFolder In myFolder.SubFolders
        For Each myFile In mySubFolder.Files
            If myFile.Name Like "Done" Then
                MsgBox myFile.Name
                Exit For
            End If
        Next

        MsgBox "Else"
    Next
Next

End Sub

Solution

  • Sub fsoobject()
    Dim fso As New FileSystemObject
    dim f As Folder
    dim  sf As Folder
    dim mySubFolder as folder 
    dim  myFile As File
     Set f = fso.GetFolder("C:\Users\jpmehta\Desktop")
     dim found as boolean 'flag if found 
     For Each sf In f.SubFolders
         For Each mySubFolder In myFolder.SubFolders
             For Each myFile In mySubFolder.Files
                 If myFile.Name Like "Done*.*" Then
                      MsgBox mysubfolder.path & "\" & myFile.Name
                      found = true 'we found it
                      Exit For 'so stop
                  End If
            Next myFile
            if found then exit for  'cascade exit
        Next MySubFolder
        if found then exit for 'and again
     next sf
    
     End Sub