gpt4 book ai didi

vba - 列出文件夹和子文件夹中的文件以及 .txt 文件的路径

转载 作者:行者123 更新时间:2023-12-02 14:13:08 26 4
gpt4 key购买 nike

我有一个 Excel 工作表,其中包含一个包含目录路径的单元格,我想要一个宏来搜索目录和任何子目录并列出 .txt 文件中的文件以及每个文件的完整路径。

这就是我目前发现的,看起来它应该找到文件,除了路径是硬编码的并且它对结果没有任何作用。

有什么想法可以改变它以满足我的需要吗?

Sub LoopThroughFiles()
Dim StrFile As String
StrFile = Dir("C:\Work\NCL\nCLs\histogram_addition\TestData\Input\RTE\")
Do While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
Loop
End Sub

最佳答案

下面是使用递归调用从 FileSystemObject() 示例拼凑而成的方法。如果需要,对结果进行排序。您还可以使用其他 FileSystemObject() 方法按 .txt 扩展名进行过滤:

    Sub Sample()
ShowFolderList ("C:\temp")
End Sub

Sub ShowFolderList(folderspec)
Dim fs, f, f1, fc, s, sFldr
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderspec)
Set fc = f.SubFolders
For Each f1 In fc
If Right(f1, 1) <> "\" Then ShowFolderList f1 & "\" Else ShowFolderList f1
Next
Set fc = f.Files
For Each f1 In fc
Debug.Print folderspec & f1.Name
Next
End Sub

写入文件:

    Option Explicit

Dim file As Object
Dim fs As Object

Sub go()
Set fs = CreateObject("Scripting.FileSystemObject")
Set file = fs.OpenTextFile("C:\temp2\results3.txt", 2, True) ' 2=ForWriting, replace
ShowFolderList "C:\temp\"
file.Close
MsgBox "done"
End Sub

Sub ShowFolderList(folderspec)
On Error GoTo local_err
Dim f, f1, fc, s, sFldr
Set f = fs.GetFolder(folderspec)
Set fc = f.SubFolders
For Each f1 In fc
If Right(f1, 1) <> "\" Then ShowFolderList f1 & "\" Else ShowFolderList f1
Next
Set fc = f.Files
For Each f1 In fc
file.writeline folderspec & f1.Name
Next
local_exit:
Exit Sub
local_err:
MsgBox Err & " " & Err.Description
Resume local_exit
Resume
End Sub

关于vba - 列出文件夹和子文件夹中的文件以及 .txt 文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20219362/

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