![]() |
#1
|
|||
|
|||
![]()
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 Last edited by Carchee; 12-18-2013 at 02:13 PM. |
|
![]() |
||||
Thread | Thread Starter | Forum | Replies | Last Post |
![]() |
AtaLoss | Word VBA | 37 | 09-22-2021 12:04 PM |
![]() |
redhin | Word VBA | 5 | 03-05-2013 05:42 AM |
![]() |
ubns | Word VBA | 7 | 08-16-2012 10:33 PM |
Multiple Headers in Same Worksheet | Tom | Excel | 3 | 05-18-2011 03:22 PM |
Multiple Headers | boutells | Word | 1 | 06-05-2009 12:04 AM |