Search and replace in the header of Word Documents

K

Kelly

I need to be able to do a search and replace in the header of Word
documents. The following VBS code works on the body of Word documents, but
not the header. Help much appreciated.

Const wdReplaceAll = 2
Const END_OF_FILE = 6
Const MOVE_SELECTION = 0

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add()

Do While objPath =""
objPath = InputBox("Enter path (C:\Junk): ", "File")
Loop

objSearch = InputBox("Enter search string: ", "Search")
objReplace = InputBox("Enter replace string: ", "Replace")

objWord.FileSearch.Filename = "*.doc"
objWord.FileSearch.LookIn = objPath
objWord.FileSearch.SearchSubfolders = False
objWord.FileSearch.Execute

objWord.Visible = FALSE

Set objWord2 = CreateObject("Word.Application")

For Each objFile in objWord.FileSearch.FoundFiles
objWord2.visible = FALSE
Set objDoc2 = objWord2.Documents.Open(objFile)
set objSelection = objWord2.Selection
objSelection.Find.Text = objSearch
objSelection.Find.Forward = TRUE
objSelection.Find.MatchWholeWord = FALSE
objSelection.Find.Replacement.Text = objReplace
objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
If Not objDoc2.Saved Then
objDoc2.Save
End If
objDoc2.Close
Next
objword2.Quit
objWord.Quit
Set objWord = Nothing
Set objWord2 = Nothing
MsgBox("Finished")
 
R

Russ

You might be able to adapt this subroutine that updates all fields to do
what you need.
Sub UpdateAllFields()
Dim oStory As Range
For Each oStory In ActiveDocument.StoryRanges
oStory.Fields.Update
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
oStory.Fields.Update
Wend
End If
Next oStory
Set oStory = Nothing
End Sub

From VBA Help for .StoryType:
Returns the story type for the specified range, selection, or bookmark. Can
be one of the following WdStoryType constants: wdCommentsStory,
wdEndnotesStory, wdEvenPagesFooterStory, wdEvenPagesHeaderStory,
wdFirstPageFooterStory, wdFirstPageHeaderStory, wdFootnotesStory,
wdMainTextStory, wdPrimaryFooterStory, wdPrimaryHeaderStory, or
wdTextFrameStory. Read-only Long.
 
K

Kelly

Thanks Russ,
It looks good. I'm working with it now and I'll let you know how I do.
Kelly
 

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