2

我已经进行了几次搜索,但在使用现在不存在的 .filesearch 时很难找到正确的代码 - 我已经研究过同时使用 Dir 和 FileSystemObject 但在搜索后使用循环时毫无疑问...我希望你能帮助我得出一个更简单的结论!

简而言之,我当前的代码在一个文件夹中搜索所有 excel 文件,然后打开第一个,执行它需要执行的操作,关闭它,然后打开下一个搜索到的文件。提前致谢!

FilePath = "S:\My\File\Path"
FileSpec = ".xls"

Set FS = Application.FileSearch
    With FS
        .LookIn = FilePath
        .Filename = FileSpec
        .Execute
    End With

For b = 1 To FS.FoundFiles.Count
    StrFile = FS.FoundFiles(b)

Set mobjXL = New Excel.Application
With mobjXL

    .Visible = False

'REST OF CODE HERE

next b
4

2 回答 2

3

这应该让你指出正确的方向:

Sub Your_Sub()

Dim FSO as Object
Dim FSO_FOLDER AS Object
Dim FSO_FILE as Object
Dim FILE_PATH as String
Dim FILE_EXT as String

FILE_PATH = "S:\My\File\Path"
FILE_EXT = "xls"

''Create FileSystem Objects
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO_FOLDER = FSO.GetFolder(FILE_PATH)

If FSO_FOLDER.Files.Count > 0 Then

    ''Loop through each File in Folder    
    For Each FSO_FILE IN FSO_FOLDER.Files

       ''Test extension
       If FSO.GetExtensionName(FSO_FILE.Name) = FILE_EXT Then
           ''Do your thing here
       Else:End if

    Next

Else

Msgbox "No Files Found at " & FILE_PATH

End If

Set FSO = Nothing
Set FSO_FOLDER = Nothing

End Sub
于 2013-07-16T10:02:34.640 回答
1

Application.FileSearch对于那些希望通过尽可能少的修改使依赖的旧代码再次工作的人,这里有一个可以用作替代的类:

https://github.com/MonsieurV/VBA.Application.FileSearch

您所要做的就是将您Set fs = Application.FileSearch的替换为:

Dim fs As YtoFileSearch
Set fs = New YtoFileSearch

并像往常一样使用它:

With fs
    .NewSearch
    .LookIn = "D:\User\Downloads\"
    .fileName = "*.pdf"
    If .Execute() > 0 Then
        Debug.Print "Found these PDF files:"
        For i = 1 To .FoundFiles.Count
           Debug.Print .FoundFiles(i)
       Next
    Else
        Debug.Print "Nothing found"
    End If
End With

如果您没有遗留代码问题,最好直接使用Scripting.FileSystemObjectDir()(请参阅UberNubIsTrue 答案

于 2015-07-19T00:04:58.130 回答