CHRIS RAE'S VBA PAGES
Module: | AddressWholeDocumentText |
Description: | Run a search and replace on the whole text of the document including sectioned headers and footers. The routine can easily be altered to perform a different operation. |
' Written by Scott Matthewman (scott@direct-image.co.uk) 28/6/99 and slightly altered by Chris Rae.
Option Explicit
Sub RunAllSearchAndReplaces()
' Call this routine to perform the complete search and
' replace - changed by CLR to use ActiveDocument instead
' of a passed Document object for simplicity's sake.
Dim rgLoop As Word.Range
Dim secLoop As Word.Section
Dim hfLoop As Word.HeaderFooter
For Each rgLoop In ActiveDocument.StoryRanges
Select Case rgLoop.StoryType
Case wdEvenPagesFooterStory, wdEvenPagesHeaderStory, _
wdFirstPageFooterStory, wdFirstPageHeaderStory, _
wdPrimaryFooterStory, wdPrimaryHeaderStory
Case Else
RunSRthroughRange rgLoop
Do Until (rgLoop.NextStoryRange Is Nothing)
Set rgLoop = rgLoop.NextStoryRange
RunSRthroughRange rgLoop
Loop
End Select
Next rgLoop
For Each secLoop In ActiveDocument.Sections
For Each hfLoop In secLoop.Headers
RunSRthroughRange hfLoop.Range
Next hfLoop
For Each hfLoop In secLoop.Footers
RunSRthroughRange hfLoop.Range
Next hfLoop
Next secLoop
End Sub
Private Sub RunSRthroughRange(DoTo As Range)
' This routine performs the actual search and replace -
' any other operation can of course be performed on the range.
DoTo.Find.Execute FindText:="hi", ReplaceWith:="hello", Replace:=wdReplaceAll
End Sub
You're free to use these routines for anything you want - all I ask is that for commercial use you give me credit somewhere. You may instead want to head back to the index for my Visual Basic for Applications Pages or the main routines archive page.