PDA

View Full Version : Problems with Find and Replace



AndrewPerl
02-03-2006, 01:43 PM
I am having issues with the Find and Replace function in Word. The following code only replaces the tag [CLIENT NAME] in the body of the document. It ignores all tags that appear in text boxes and in headers or footers.

If I manually invoke the Find and Replace everything works fine. The following code is one of many iterations I have tried. Is it something to do with the range? I have tried range with start and end set to 0. I have also tried ActiveDocument.Content... all with no success. Please help.

Public Sub Customize_Doc()
Dim CL_Name, Client_Replace, Quarter, Doc_Year
CL_Name = "[CLIENT NAME]"
Quarter = "[QUARTER]"
Doc_Year = "[YEAR]"
Client_Replace = InputBox("Enter the name of the client.", "Client Name")
Set myrange = ActiveDocument.Content
myrange.Find.Execute Findtext:=CL_Name, ReplaceWith:=Client_Replace, Replace:=wdReplaceAll
End Sub


Thanks,

Andrew Perl in Kansas City

fumei
02-04-2006, 02:27 PM
1. Could you please use the underscore character ( _ ) in your code? It really helps with those of us not using huge screen resolutions.myrange.Find.Execute Findtext:=CL_Name, _
ReplaceWith:=Client_Replace, Replace:=wdReplaceAll
2. You are likely using a later version of Word that contains Stories. For example, headers and footers are in their own Story. If you want to use Range with all the stories you must loop through all the stories.

3. To look through textboxes you MUST specifically use the proper story (wdTextFrameStory - the constant = 5).

Here is code that will explicitly loop through ALL stories, including footnotes, endnotes, etc etc. You can use the ObjectBrowser to get the constants if you want . I just loop through constant 1 to 11, which is all stories. Or you can use the ObjectBrowser to get the names - like wdTextframeStory, wdMainTextStory etc. etc.

Again - PLEASE use the underscore character when posting code. Thanks.Public Sub Customize_Doc()
Dim CL_Name, Client_Replace, Quarter, Doc_Year As String
Dim var
CL_Name = "[CLIENT NAME]"
Quarter = "[QUARTER]"
Doc_Year = "[YEAR]"
Client_Replace = InputBox("Enter the name of the client.", "Client Name")
For var = 1 To 11
On Error Resume Next
With ActiveDocument.StoryRanges(var).Find
.Execute Findtext:=CL_Name, ReplaceWith:=Client_Replace, _
Replace:=wdReplaceAll
End With
Next
End Sub

AndrewPerl
03-01-2006, 01:50 PM
Thanks for the help on this. I got pulled away from this project and forgot about it until today. I had figured out the Story issue since I posted this message. This is somewhat annoying behavior on the part of MS-Word.