2

所有试图找到这个问题的解决方案的搜索都提出了与我正在寻找的相反的结果。我不需要从文件夹内的搜索中排除文件,而是将它们全部包含在内。

我的问题是我的搜索返回文件夹中除 1 之外的所有文件。每次未找到的 1 文件是完全随机的。我尝试过同时使用 Dir() 和 FSO 方法、不同的目录、不同数量的文件等。无论我尝试什么,列表中总是缺少 1 个文件。

以下是我的代码的简化片段:

目录()版本:

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 之外的所有文件(随机)。

4

1 回答 1

4

在这两个版本中,SourceFile = Dir()都高于ActiveCell.Value = SourceFile. 这会导致在将文件名添加到列表之前跳到列表中的下一个文件,从而丢失第一个文件。

更正的代码:

目录()版本:

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
于 2015-08-19T20:10:36.267 回答