gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:59:55 27 4
gpt4 key购买 nike

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

我的问题是,我的搜索返回文件夹内除 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

关于excel - Dir() 和 FSO 都缺少 1 个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103915/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com