Public Sub BatchReplaceAll()
Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
Dim i As Long
'Enter the directory you want to search here.
PathToUse = "c:\files\WordFiles"
On Error Resume Next
'Closes all open documents before beginning
Documents.Close savechanges:=wdPromptToSaveChanges
FirstLoop = True
'Set the directory and type of file to batch process
With Application.FileSearch
.NewSearch
.LookIn = PathToUse
'INCLUDE SUBFOLDERS?
.SearchSubFolders = True
.FileName = "*.doc"
.MatchTextExactly = True
.FileType = msoFileTypeAllFiles
If .Execute() Then
For i = 1 To .FoundFiles.Count
'Open document
Set myDoc = Documents.Open(.FoundFiles(i))
'Here are two examples of the search and replace code.
'The first searches for text, the second searches for a link.
'You have to hit Alt-F9 to show field codes before starting the
'macro to search for links.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "Replace Me"
.Replacement.Text = "This was replaced."
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "/fakedirectory/fakesubdirectory/fakefile.htm"
.Replacement.Text = "/fakedirectory2/fakesubdirectory2/fakefile2.htm"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
'These two lines update the field codes you just updated. They
'aren't necessary if you're not searching for links.
Selection.WholeStory
Selection.Fields.Update
'Close the modified document after saving changes
myDoc.Close savechanges:=wdSaveChanges
Next i
End If
End With
End Sub
posted by Four Flavors at 2:10 PM on March 16, 2007