Find names of docs in sub folders?

E

Ed

I found a macro which writes the names of all files in a folder to a
document. I would like to have this macro search subfolders, too, and write
those doc names to the document. Can someone point me in the right
direction, please?

Ed

Sub ListDocNames()

Dim sMyDir As String

Dim sDocName As String



' The path to obtain files.

sMyDir = "C:\Documents and Settings\Folder1\Folder2"

sDocName = Dir(sMyDir & "\*.doc")



' Add new document.

Documents.Add



' Insert file names in document.

While sDocName <> ""

' Insert filename in document.

Selection.TypeText sMyDir & "\" & sDocName & vbCr

' Get next file name.

sDocName = Dir()

Wend



' Save file

ActiveDocument.SaveAs FileName:=sMyDir & "\File Paths.doc"

ActiveDocument.Close



End Sub
 
S

Steve Lang

Hi Ed,

Use the Application.FileSearch method:

Dim i As Long
With Application.FileSearch
'Search in foldername
.LookIn = "C:\My Documents"
.SearchSubFolders = True
.FileName = "*.doc"
.Execute
For i = 1 To .FoundFiles.Count
Debug.Print (.FoundFiles(i))
Next i
End With


HTH and have a great day!

Steve
 
E

Ed

Thanks for the reply, Steve. I'm sorry to sound dense on this, but I don't
know how to use it. Do I place it inside the code I already have? Or is it
supposed to work as a stand-alone module? I did put it in its own module
and ran it, but if it wrote the file names anywhere, I can't find the doc.

Ed
 
S

Steve Lang

Hi ed,

The original code was only outputting the filenames to the immediate window
in the Visual Basic Environment. Use this to get the data to output to a new
document:

Sub Foo()
Dim i As Long
Dim oDoc As Document
Set oDoc = Documents.Add
With Application.FileSearch
'Search in foldername
.LookIn = "C:\My Documents"
.SearchSubFolders = True
.FileName = "*.*"
.Execute
For i = 1 To .FoundFiles.Count
oDoc.Range.InsertAfter (.FoundFiles(i)) & vbCr
Next i
End With
Set oDoc = Nothing
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top