|
 |
|
Another handy method for defining any replacement text
string and even a graphic is to use AutoText. Fellow MVP Graham
Mayor has posted instructions for using this method here:
Replace w/AutoText |
|
Unfortunately the character code ^c doesn't work in the "Find what"
window. Even find strings constructed using wildcards are
limited to 255 characters as shown below. |
|
 |
|
If you try to set a find or replace strings that are > 255 characters in length in VBA, a run-time error is
generated. |
|
 |
|
I worked with Dave Lett and Helmut Weber, who both contribute regularly
in
the Word VBA newsgroup, to develop a macro that would perform a find and
replace routine where the text you are looking for exceeds 255 characters. The
process involves defining the .Find.Text string as the first 250 characters of
your text. If this segment is found, then the selection is extended to
include the entire length
of your specified text and then a comparison is made of the find text string and
extended selection. If a match
occurs, the selection.text is replaced with the specified replacement
text. In this solution, both the find and replace strings are
defined in a separate document. |
|
Here is the macro code: |
Sub LongStringFindReplace()
Dim oSourceDoc As Document
Dim srchTxt As String
Dim replaceRng As Range
Dim i As Long
Set oSourceDoc = Documents.Open(FileName:="C:\Long String Source.doc")
'Establish find string
srchTxt = oSourceDoc.Paragraphs(1).Range.Text
srchTxt = Left(srchTxt, Len(srchTxt) - 1) 'Remove
paragraph mark
'Establish replace text and copy to clipboard
Set replaceRng = oSourceDoc.Paragraphs(2).Range
replaceRng.MoveEnd Unit:=wdCharacter, Count:=-1
'Remove paragraph mark
replaceRng.Copy
oSourceDoc.Close
ActiveDocument.Range(0, 0).Select
If Len(srchTxt) > 250 Then
i = Len(srchTxt) - 250
With Selection.Find
.Text = Left(srchTxt, 250)
.Forward = True
.Wrap = wdFindContinue
Do While .Execute
'Move end of
selection to match length of srchTxt
Selection.MoveEnd Unit:=wdCharacter, Count:=i
'Compare selection
to search string
If Selection.Text = srchTxt Then
'replace selction with clipboard contents
Selection.Paste
Else
Selection.MoveRight
End If
Loop
End With
Else
ResetFRParameters
With Selection.Find
.Text = srchTxt
.Replacement.Text = "^c"
.Forward = True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
End If
End Sub
Sub ResetFRParameters()
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
End Sub |
|
Need help applying macros? See fellow MVP Graham
Mayor's
Guide for
Installing Macros |
|
|
Looking for something else?
|
|
|
|
|