寻找解决此问题的所有搜索尝试都与我正在寻找的相反。我不需要从文件夹内的搜索中排除文件,而是将它们全部包括在内。
我的问题是我的搜索返回的是文件夹中除1外的所有文件。每次都找不到的1个文件是完全随机的。我尝试同时使用Dir()和FSO方法,不同的目录,不同数量的文件等。无论我怎样尝试,列表中总是缺少1个文件。
这是我的代码的简化片段:
Dir()版本:
FilePath = "C:\Test\"
SourceFile = Dir(FilePath & "*.xls*")
Do While SourceFile <> ""
SourceFile = Dir()
ActiveCell.Value = SourceFile
ActiveCell.Offset(1, 0).Activate
Loop
FSO版本:
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(FilePath)
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
If File.Name <> "" Then
SourceFile = Dir()
ActiveCell.Value = SourceFile
ActiveCell.Offset(1, 0).Activate
End If
Next
End Sub
同样,它们都返回除1(随机)之外的所有文件。
在两个版本中,SourceFile = Dir()
均位于上方ActiveCell.Value = SourceFile
。这会导致在将文件名添加到列表之前,通过跳到列表中的下一个文件来丢失第一个文件。
更正的代码:
Dir()版本:
FilePath = "C:\Test\"
SourceFile = Dir(FilePath & "*.xls*")
Do While SourceFile <> ""
ActiveCell.Value = SourceFile
ActiveCell.Offset(1, 0).Activate
SourceFile = Dir()
Loop
FSO版本:
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(FilePath)
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
If File.Name <> "" Then
ActiveCell.Value = File.Name
ActiveCell.Offset(1, 0).Activate
End If
Next
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句