Searching for text in all the documents in a folder and its subfolders

L

Larry

I have a couple of macros that can run a macro in all the documents in a
folder. But I want to do something that those macros can't handle. I
want to do a Find (not a replace, just a find) that will stop at each
occurrence of the found text in all the documents in a folder (and
optionally its subfolders). This is difficult because the code in the
below macro to close the current document and move on to the next
document must not run until all the searched-for strings in the first
document are found. In the below code, I've commented out the Close
Document code.

Normally, if I do a Windows Find for the documents that contain the
text, I still have to open each document individually and search again
for the text. I want to make it all one continuous search, opening a
document, stopping at each instance of the found text as I repeat the
command, and then when there are no more to be found in that document,
closing it and opening the next document. Can that be done?

Thanks,
Larry

Dim sFileName As String
Dim sFolder As String

'Replace with your own foldername
sFolder = "C:\Documents\Tests\"
sFileName = Dir(sFolder & "*.doc")

While sFileName <> ""
Documents.Open (sFolder & sFileName)

'run macro

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "powerful"
.Forward = True
.Wrap = wdFindContinue
.MatchCase = False
End With
Selection.Find.Execute

' commented this line out.
' ActiveDocument.Close savechanges:=wdSaveChanges
sFileName = Dir()
Wend
 
J

Jezebel

Simplest is to put the find.execute within a loop that continues until
..Found returns false --

With Selection.Find
.ClearFormatting
.Text = "powerful"
.Forward = True
.Wrap = wdFindContinue
.MatchCase = False

do
.execute
if not .Found then
exit do
end if

... text found ... call your processing function here

loop

End With


Also, rather than use the Selection object, it would be better to work
directly with the document ranges you want to search:

Dim pDoc as Word.Document
Set pDoc = Documents.Open (sFolder & sFileName)

With pDoc.StoryRanges(wdMainTextStory).Find (or whatever ranges you
need to search in)
 

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