I've done several searches and I'm having trouble to find the right code when using the now non-existent .filesearch - I've looked into using both Dir and FileSystemObject but with nothing short of confusion when using a loop after the search... I'm hoping you might be able to help me come to an easier conclusion!
In short, my current code searches a folder for all excel files, and opens the first, does what it needs to do with it, closes it, and opens the next searched file. Thanks in advance!
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
This should get you pointed in the right direction:
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
For those that want to make old code that rely on Application.FileSearch
work again with as little modification as possible, here a class that you can use as a replacement:
https://github.com/MonsieurV/VBA.Application.FileSearch
All you have to do is replacing your Set fs = Application.FileSearch
by:
Dim fs As YtoFileSearch
Set fs = New YtoFileSearch
And use it as usual :
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
If you don't have legacy code issues, better use directly Scripting.FileSystemObject
or Dir()
(see UberNubIsTrue answer)
来源:https://stackoverflow.com/questions/17671725/application-filesearch-in-excel-2007-w-loop