Replace second instance of string

S

Shawn G.

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
 
H

Helmut Weber

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

--
Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 
S

Shawn G.

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?
 
H

Helmut Weber

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...
 

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