列出文件夹和子文件夹中的.txt文件path的文件

我有一个Excel单张,其中包含一个目录的path单元格,我想要一个macros,search目录和任何子目录,并列出文件的.txt文件,每个文件的完整path。

这是目前我发现,它看起来应该find的文件,除了path是硬编码,并没有做任何事情的结果。

任何想法如何我可以改变它,以适应我的需求?

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 

下面是一个使用recursion调用从FileSystemObject()示例拼凑在一起的方法。 根据需要对结果进行sorting。 您还可以使用其他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