Dir() 和 FSO 都缺少 1 个文件

Dir() and FSO Both Missing 1 File

为找到此问题的解决方案而进行的所有搜索尝试都得出了与我正在寻找的相反的结果。我不需要从文件夹内的搜索中排除文件,而是将它们全部包括在内。

我的问题是我的搜索 return 搜索文件夹中除 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

同样,这两个 return 除了 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