search and replace individual documents

H

Hilary Ratner

Hi.

I have a user with hundreds of individual Word docs. She
wants to open each doc and replace a phrase with another
phrase and save as a new doc.

Rather than open, search and replace, and save each doc
individually, is there a way to make this process faster?

My solutions were:

1. Create a master document containing the individual docs
and then do a global search and replace. (I haven't had
much luck with master documents in the past so I am a
little scared to try that.)

2. Use macros. Is it possible to create a macro that would
open, search and replace, and save as?

Is there an easier way? Any thoughts are appreciated!

Thanks!

Hilary
 
P

Pat Garard

G'Day Hilary,

Maybe I have just been lucky, but I have NEVER had
a problem with Master Documents - perhaps it's the
virtuous life I lead! You could give it a try with, say, 10
or 20 of the docs. If you COPY the docs to Folder set
up for this "conversion" purpose, you may well find
it works well (you've nothing to lose) - give it a try.

However, a key issue is the fact that you want to
snip>
"save as a new doc"
snip>.

This would suggest a Macro approach, as long as
the "new" name can be derived from the old name
eg newDocName = oldDocName & "_New".
--
Regards,
Pat Garard
Australia

______________________________________
 
C

Chad DeMeyer

Hilary,

Following is some code I wrote to find specific words or phrases in a whole
directory of Word docs. The Windows search interface allows you to search
for files "Containing text ...", but this won't work for Word documents that
are Protected For Forms, and the majority of documents I needed to search in
were online forms that were protected in this way, so I wrote this macro to
do the search. I believe it could be easily adapted for your needs.

Sub FindFormsWithSpecifiedText()
Dim fs As New Scripting.FileSystemObject
Dim tFolder As Folder, aFile As File, testDoc As Document
Dim strAdd As String, strText As String

Documents.Add
strText = InputBox("Text to find in folder path:")

WordBasic.DisableAutoMacros
Set tFolder = fs.GetFolder([supply a folder path here])
For Each aFile In tFolder.Files
Set testDoc = Documents.Open(aFile.Path)
On Error Resume Next
If Not testDoc.ProtectionType = wdNoProtection Then _
testDoc.Unprotect [supply a standard password here]
If testDoc.ProtectionType = wdNoProtection Then
With Selection.Find
.ClearFormatting
.Text = strText
.Wrap = wdFindContinue
End With
Selection.Find.Execute
If Selection.Find.Found Then
strAdd = testDoc.Name & vbCr
Else
strAdd = ""
End If
Else
strAdd = testDoc.Name & "could not be unprotected with standard
" & _
"password. No search performed." & vbCr
End If
testDoc.Close wdDoNotSaveChanges
Selection.TypeText strAdd
Next aFile
End Sub

The macro tests each document in the specified folder for protection. If
the document is protected, the macro attempts to unprotect it using a
standard password that you specify in the code. If it is able to unprotect
the document with that password, it searches for the specified text. It
generates a report in a new blank doc that lists all the files which
contained the specified text, as well as any files that couldn't be
unprotected with the standard password. Mine was set up to generate a
report because I had to use a change control process to modify each form,
but you could simply do a replace for each Find.Found. Also, all the
documents I needed to search in were located in a specific Workgroup
Templates location, so I hard-coded that into my procedure, but you could
also use something like:

Dim oShell as Object
Dim oFolder as Object
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.BrowseForFolder(0, "Select a Folder", 0, ssfDrives)

This would allow the user to browse for a specific folder whose files they
want to search.

Hope this is enough to get you started. Regards,
Chad DeMeyer
 
H

Hilary

Hi Chad.

Hmm. I have a directory of over 100 docs and ALL of them
contain the text that needs to be changed.

I just want to make sure I understand what you are saying.
This code would only help me to find keywords, but not
automate the process of changing the words, would it?

Thanks!

Hilary

-----Original Message-----
Hilary,

Following is some code I wrote to find specific words or phrases in a whole
directory of Word docs. The Windows search interface allows you to search
for files "Containing text ...", but this won't work for Word documents that
are Protected For Forms, and the majority of documents I needed to search in
were online forms that were protected in this way, so I wrote this macro to
do the search. I believe it could be easily adapted for your needs.

Sub FindFormsWithSpecifiedText()
Dim fs As New Scripting.FileSystemObject
Dim tFolder As Folder, aFile As File, testDoc As Document
Dim strAdd As String, strText As String

Documents.Add
strText = InputBox("Text to find in folder path:")

WordBasic.DisableAutoMacros
Set tFolder = fs.GetFolder([supply a folder path here])
For Each aFile In tFolder.Files
Set testDoc = Documents.Open(aFile.Path)
On Error Resume Next
If Not testDoc.ProtectionType = wdNoProtection Then _
testDoc.Unprotect [supply a standard password here]
If testDoc.ProtectionType = wdNoProtection Then
With Selection.Find
.ClearFormatting
.Text = strText
.Wrap = wdFindContinue
End With
Selection.Find.Execute
If Selection.Find.Found Then
strAdd = testDoc.Name & vbCr
Else
strAdd = ""
End If
Else
strAdd = testDoc.Name & "could not be unprotected with standard
" & _
"password. No search performed." & vbCr
End If
testDoc.Close wdDoNotSaveChanges
Selection.TypeText strAdd
Next aFile
End Sub

The macro tests each document in the specified folder for protection. If
the document is protected, the macro attempts to unprotect it using a
standard password that you specify in the code. If it is able to unprotect
the document with that password, it searches for the specified text. It
generates a report in a new blank doc that lists all the files which
contained the specified text, as well as any files that couldn't be
unprotected with the standard password. Mine was set up to generate a
report because I had to use a change control process to modify each form,
but you could simply do a replace for each Find.Found. Also, all the
documents I needed to search in were located in a specific Workgroup
Templates location, so I hard-coded that into my procedure, but you could
also use something like:

Dim oShell as Object
Dim oFolder as Object
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.BrowseForFolder(0, "Select a Folder", 0, ssfDrives)

This would allow the user to browse for a specific folder whose files they
want to search.

Hope this is enough to get you started. Regards,
Chad DeMeyer

Hilary Ratner said:
Hi.

I have a user with hundreds of individual Word docs. She
wants to open each doc and replace a phrase with another
phrase and save as a new doc.

Rather than open, search and replace, and save each doc
individually, is there a way to make this process faster?

My solutions were:

1. Create a master document containing the individual docs
and then do a global search and replace. (I haven't had
much luck with master documents in the past so I am a
little scared to try that.)

2. Use macros. Is it possible to create a macro that would
open, search and replace, and save as?

Is there an easier way? Any thoughts are appreciated!

Thanks!

Hilary


.
 
C

Chad DeMeyer

As the code is currently written, it finds keywords, because I couldn't
replace the keywords without documenting my changes and formally reissuing
the documents. However, with a few modifications, the code could be made to
replace any instance of a word or phrase with another word or phrase, rather
than just generating a report of all the docs in which a word or phrase was
found. The code I supplied was intended to be a starting point, but it will
need this and probably a few other modifications to be suited to your needs.

Regards,
Chad DeMeyer



Hilary said:
Hi Chad.

Hmm. I have a directory of over 100 docs and ALL of them
contain the text that needs to be changed.

I just want to make sure I understand what you are saying.
This code would only help me to find keywords, but not
automate the process of changing the words, would it?

Thanks!

Hilary

-----Original Message-----
Hilary,

Following is some code I wrote to find specific words or phrases in a whole
directory of Word docs. The Windows search interface allows you to search
for files "Containing text ...", but this won't work for Word documents that
are Protected For Forms, and the majority of documents I needed to search in
were online forms that were protected in this way, so I wrote this macro to
do the search. I believe it could be easily adapted for your needs.

Sub FindFormsWithSpecifiedText()
Dim fs As New Scripting.FileSystemObject
Dim tFolder As Folder, aFile As File, testDoc As Document
Dim strAdd As String, strText As String

Documents.Add
strText = InputBox("Text to find in folder path:")

WordBasic.DisableAutoMacros
Set tFolder = fs.GetFolder([supply a folder path here])
For Each aFile In tFolder.Files
Set testDoc = Documents.Open(aFile.Path)
On Error Resume Next
If Not testDoc.ProtectionType = wdNoProtection Then _
testDoc.Unprotect [supply a standard password here]
If testDoc.ProtectionType = wdNoProtection Then
With Selection.Find
.ClearFormatting
.Text = strText
.Wrap = wdFindContinue
End With
Selection.Find.Execute
If Selection.Find.Found Then
strAdd = testDoc.Name & vbCr
Else
strAdd = ""
End If
Else
strAdd = testDoc.Name & "could not be unprotected with standard
" & _
"password. No search performed." & vbCr
End If
testDoc.Close wdDoNotSaveChanges
Selection.TypeText strAdd
Next aFile
End Sub

The macro tests each document in the specified folder for protection. If
the document is protected, the macro attempts to unprotect it using a
standard password that you specify in the code. If it is able to unprotect
the document with that password, it searches for the specified text. It
generates a report in a new blank doc that lists all the files which
contained the specified text, as well as any files that couldn't be
unprotected with the standard password. Mine was set up to generate a
report because I had to use a change control process to modify each form,
but you could simply do a replace for each Find.Found. Also, all the
documents I needed to search in were located in a specific Workgroup
Templates location, so I hard-coded that into my procedure, but you could
also use something like:

Dim oShell as Object
Dim oFolder as Object
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.BrowseForFolder(0, "Select a Folder", 0, ssfDrives)

This would allow the user to browse for a specific folder whose files they
want to search.

Hope this is enough to get you started. Regards,
Chad DeMeyer

Hilary Ratner said:
Hi.

I have a user with hundreds of individual Word docs. She
wants to open each doc and replace a phrase with another
phrase and save as a new doc.

Rather than open, search and replace, and save each doc
individually, is there a way to make this process faster?

My solutions were:

1. Create a master document containing the individual docs
and then do a global search and replace. (I haven't had
much luck with master documents in the past so I am a
little scared to try that.)

2. Use macros. Is it possible to create a macro that would
open, search and replace, and save as?

Is there an easier way? Any thoughts are appreciated!

Thanks!

Hilary


.
 
D

Dayo Mitchell

From previous posts, here is some code designed to do what you want--there's
an FAQ on the MVP site but apparently it is out of date.

DM

Greg said:
Then
Graham said:
Ibby's old code on that page has been much modified but the updates have not
made it to the site yet. Try the following code:

Public Sub BatchReplaceAnywhere()
'Macro by Doug Robbins - 1st March 2004
'with additional input from Peter Hewett
'to replace text in all the documents in a folder

Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim rngstory As Word.Range
Dim FindText As String
Dim Replacement As String

' Get the folder containing the files
With Dialogs(wdDialogCopyFile)
If .Display <> 0 Then
PathToUse = .Directory
Else
MsgBox "Cancelled by User"
Exit Sub
End If
End With

'Close any documents that may be open
If Documents.Count > 0 Then
Documents.Close Savechanges:=wdPromptToSaveChanges
End If

FirstLoop = True

If Left(PathToUse, 1) = Chr(34) Then
PathToUse = Mid(PathToUse, 2, Len(PathToUse) - 2)
End If

myFile = Dir$(PathToUse & "*.doc")

While myFile <> ""
'Get the text to be replaced and the replacement
If FirstLoop = True Then
FindText = InputBox("Enter the text that you want to replace.",
"Batch Replace Anywhere")
If FindText = "" Then
MsgBox "Cancelled by User"
Exit Sub
End If
Tryagain:
Replacement = InputBox("Enter the replacement text.", "Batch
ReplaceAnywhere ")
If Replacement = "" Then
Response = MsgBox("Do you just want to delete the found text?",
vbYesNoCancel)
If Response = vbNo Then
GoTo Tryagain
ElseIf Response = vbCancel Then
MsgBox "Cancelled by User."
Exit Sub
End If
End If
FirstLoop = False
End If


'Open each file and make the replacement
Set myDoc = Documents.Open(PathToUse & myFile)
' Fix the skipped blank Header/Footer problem
MakeHFValid
' Iterate through all story types in the current document
For Each rngstory In ActiveDocument.StoryRanges
' Iterate through all linked stories
Do
SearchAndReplaceInStory rngstory, FindText, Replacement
' Get next linked story (if any)
Set rngstory = rngstory.NextStoryRange
Loop Until rngstory Is Nothing
Next
'Close the file, saving the changes.
myDoc.Close Savechanges:=wdSaveChanges
myFile = Dir$()
Wend
End Sub

Public Sub SearchAndReplaceInStory(ByVal rngstory As Word.Range, _
ByVal strSearch As String, _
ByVal strReplace As String)
'This routine supplied by Peter Hewett
Do Until (rngstory Is Nothing)
With rngstory.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = strSearch
.Replacement.Text = strReplace
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceAll
End With
Set rngstory = rngstory.NextStoryRange
Loop
End Sub

Public Sub MakeHFValid()
'And this too
Dim lngJunk As Long
' It does not matter whether we access the Headers or Footers property.
' The critical part is accessing the stories range object
lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType
End Sub

If necessary see http://www.gmayor.com/installing_macro.htm
 

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