I figured out an answer to this - hopefully it's of some use 3 years on.
In my application, I'm replacing all occurrences of the string "{Text}" in a document with the replacement text.
The approach is to break the replacement text into "chunks" of 250 characters, and if there are any more chunks remaining, append a new replacement variable ({1} for the first chunk, {2} for the second, etc.), then repeat.
My code below runs in Word 2010 VBA:
Private Sub SearchAndReplace(search As String, replace As String)
Dim i As Integer
Dim chunks As Integer
Dim chunk As String
Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst ' Go to the start of the document
With Selection.Find
.ClearFormatting
.MatchCase = True
.MatchWholeWord = True
' We get error 5854 if the replacement text is greater than 255 characters, so need to work around
' How many 250 character "chunks" are there in the replacement text?
chunks = Round(Len(replace) / 250, 0) ' Use 250 to allow for {1}, etc.
If Len(replace) Mod 250 > 0 Then chunks = chunks + 1 ' Workaround because there's no Ceiling()
If chunks = 1 Then
.Execute FindText:="{" & search & "}", ReplaceWith:=replace, replace:=wdReplaceAll
Else
' Replace existing replacement variable (e.g. {Text}) the first chunk's replacement variable (i.e. {1})
.Execute FindText:="{" & search & "}", ReplaceWith:="{1}", replace:=wdReplaceAll
' Replace the text in chunks of less than 255 characters
For i = 1 To chunks
' Get the
chunk = Mid(replace, ((i - 1) * 250) + 1, 250)
' Add the replacement variable for the next chunk to the end of the string
If i < chunks Then chunk = chunk & "{" & (i + 1) & "}"
.Execute FindText:="{" & i & "}", ReplaceWith:=chunk, replace:=wdReplaceAll
Next i
End If
End With
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…