I need to replace the second instance of a search string. For Example:
Search text is <Insert Name>
But there are 5 of these in various places through out the document.
The replacement text would be John Doe
How would you write the VB to do this as I need to search and replace
various different text fields.
Thank you
Hi Shawn,
>I need to replace the second instance of a search string.
>How would you write the VB to do this
>as I need to search and replace
>various different text fields.
I don't know what fields are in this context.
For ordinary text, like this:
Sub Test12345()
Dim rDoc As Range
Set rDoc = ActiveDocument.Range
ResetSearch
With rDoc.Find
.Text = "last"
.Replacement.Text = "XXXX"
If .Execute Then
.Execute Replace:=wdReplaceOne
End If
End With
ResetSearch
End Sub
' ---
Public Sub ResetSearch()
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
End Sub

Signature
Greetings from Bavaria, Germany
Helmut Weber, MVP WordVBA
Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
Shawn G. - 03 Oct 2005 19:16 GMT
Thank You, that worked great but I found that Some searches I need to do are
for the 3rd or 4th instance, not just the second. How could this code be
altered for that?
> Hi Shawn,
>
[quoted text clipped - 40 lines]
> End With
> End Sub
Helmut Weber - 04 Oct 2005 09:25 GMT
Hi Shawn,
like this:
Sub ReplaceNthOccurance _
(sOrg As String, sRpl As String, n As Long)
Dim rDoc As Range
Dim c As Long ' a counter
Set rDoc = ActiveDocument.Range
c = 0
ResetSearch
With rDoc.Find
.Text = sOrg
.Replacement.Text = sRpl
If n = 1 Then
.Execute Replace:=wdReplaceOne
Exit Sub
End If
While .Execute
c = c + 1
If c = n - 1 Then
If .Execute(Replace:=wdReplaceOne) Then
Exit Sub
End If
End If
Wend
End With
ResetSearch
End Sub
Sub Test1000()
Call ReplaceNthOccurance("Franz", "11111", 1)
End Sub
' ---
Public Sub ResetSearch()
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
End Sub
Note: Having tested this once like
Call ReplaceNthOccurance("Franz", "11111", 1)
the former second instance of "Franz" is now the
first instance...
--
Greetings from Bavaria, Germany
Helmut Weber, MVP WordVBA
"red.sys" & chr(64) & "t-online.de"
Word 2002, Windows 2000
Shawn G. - 04 Oct 2005 13:56 GMT
Thanks Helmut, Worked great!
> Hi Shawn,
>
[quoted text clipped - 58 lines]
> "red.sys" & chr(64) & "t-online.de"
> Word 2002, Windows 2000