Dir()和FSO都丢失1个文件

所有的search尝试find解决这个问题已经拿出了我所期待的相反。 我不需要从一个文件夹中的search中排除文件,但包括所有文件。

我的问题是,我的search正在返回除了1以外的文件夹中的所有文件。每次没有find1文件是完全随机的。 我曾尝试使用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