我已经完成了几次搜索,而且在使用现在不存在的.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
答案 0 :(得分: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
答案 1 :(得分:1)
对于那些希望通过尽可能少的修改再次依赖void Foo()
{
Bar(new[] { 1, 2, 3 });
}
void Bar(int[] args)
{
// use args...
}
工作的旧代码的人,这里有一个可以作为替代的类:
您所要做的就是将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.FileSystemObject
(请参阅https://github.com/MonsieurV/VBA.Application.FileSearch)