无法使用fso打开文件

时间:2017-10-30 12:02:20

标签: excel-vba filesystemobject fso vba excel

我正在尝试使用FileSystemObject打开文件,但是当我尝试运行它时,系统什么都不做。不显示Debug,没有运行时错误,不编译。它只是保持不变。 我还检查了参考文献中的“MS Scripting Runtime”。 以下是我用于此的代码:

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

3 个答案:

答案 0 :(得分:0)

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 sf.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

    Dim File
    For Each File In f.Files
        If File.Name = "Done.PNG" Then
            Call Shell("Explorer.exe """ & File.Path & """", vbNormalFocus)
            Exit For
        End If
    Next

End Sub

嗯,我搜索了一下,发现了这个关键字" Shell"打开一个文件。在应用此代码时,现在它已成功执行...

答案 1 :(得分:0)

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

答案 2 :(得分:0)

此代码适用于我。简单明了:

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

For Each sf In f.SubFolders
    Set ssf = sf

    For Each myFile In ssf.Files
        If myFile.Name Like "Done" Then
            Debug.Print myFile.Name
            Exit For
        End If

    Debug.Print "Else:" & myFile.Name

    Next
Next

End Sub
  1. 设置子文件夹(Set ssf = sf)
  2. 我建议使用Debug.Print检查VBE中的循环