View Single Post
 
Old 12-18-2013, 11:56 AM
Carchee Carchee is offline Windows 7 64bit Office 2007
Advanced Beginner
 
Join Date: Dec 2013
Posts: 46
Carchee is on a distinguished road
Default Replace words within headers in multiple document

I am trying to create a macro that will go through and replace text in a header found in multiple documents.

The program opens the find and replace function where you put in your criteria and hit "replace all" then hit "close", it will then ask you if you want to do the same for all the documents in the folder, after hitting "Yes" it crashes.The code will successfully change the first documents text but then crashes word with the next document.

Please help and thank you.

Here is the code:

Code:
Option Explicit

Public Sub BatchReplaceAll()

Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
Dim myStoryRange As Range

PathToUse = "C:\Test\"

'Error handler to handle error generated whenever
'the FindReplace dialog is closed

On Error Resume Next

'Close all open documents before beginning

Documents.Close SaveChanges:=wdPromptToSaveChanges

'Boolean expression to test whether first loop
'This is used so that the FindReplace dialog will
'only be displayed for the first document

FirstLoop = True

'Set the directory and type of file to batch process

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

While myFile <> ""

    'Open document
    Set myDoc = Documents.Open(PathToUse & myFile)

    If FirstLoop Then

        'Display dialog on first loop only

        Dialogs(wdDialogEditReplace).Show

        FirstLoop = False

        Response = MsgBox("Do you want to process the rest of the files in this folder", vbYesNo)
        If Response = vbNo Then Exit Sub

    Else

        'On subsequent loops (files), a ReplaceAll is
        'executed with the original settings and without
        'displaying the dialog box again
For Each myStoryRange In ActiveDocument.StoryRanges
   If myStoryRange.StoryType <> wdMainTextStory Then
        With Dialogs(wdDialogEditReplace)
            .ReplaceAll = 1
            .Execute
        End With
    
       Do While Not (myStoryRange.NextStoryRange Is Nothing)
         Set myStoryRange = myStoryRange.NextStoryRange
          With Dialogs(wdDialogEditReplace)
            .ReplaceAll = 1
            .Execute
            End With
        Loop
    End If
Next myStoryRange

    End If

    'Close the modified document after saving changes

    myDoc.Close SaveChanges:=wdSaveChanges

    'Next file in folder

    myFile = Dir$()

Wend

End Sub
P.S. I tried search the threads for this topic and failed, sorry if this has been posted already. If it has please direct me to that thread.

Last edited by Carchee; 12-18-2013 at 02:13 PM.
Reply With Quote