excelvbams-word

Can content in Word that exceeds 255 characters be replaced?


I have a script to fill out a Word template document with information. It replaces tagged parts (e.g. <>) in the Word doc with data from Excel.

The problem I am running in to is with this section:

With wDoc.Content.Find
            .Execute FindText:="<<ad>>", ReplaceWith:=ad, Replace:=2
End With

Here I am met with run time error 5854 - string parameter too long

As far as I understand it, this is because the find and replace funtion in Word doesn't like it when the replace data is over 255 characters long.

Is there a different way of going about this to bypass the character limit?


Solution

  • It can be a solution:

      Dim r As Word.Range, i As Long
      Set r = wDoc.Content
      i = 2 ' repetitions to f&r
      While r.Find.Execute(FindText:="<<ad>>") And i > 0
        r.Text = ad
        i = i - 1
        r.End = wDoc.Content.End
      Wend
    

    Use this code fragment as a replacement of what is in the question. Don't miss to replace "<<ad>>" with the proper variable name. Also, 'ad' variable's value is expected to be renewed for every new tag.

    The idea here is to find the token then set the necessary text directly to the found range.

    The test (run in Word):

    Sub FR()
      Dim r As Word.Range, i As Long
      Dim find, repl, j As Long
      Dim wDoc As Document
      Set wDoc = ThisDocument
      find = Array("<<ad>>", "<<bc>>")
      repl = Array("==buirsdfg iuhuierhf aesgh iuhewr iuhiuher uhbuirsdfg iuhuierhf aesgh iuhewr iuhiuher uhbuirsdfg iuhuierhf aesgh iuhewr iuhiuher uhbuirsdfg iuhuierhf aesgh iuhewr iuhiuher uhbuirsdfg iuhuierhf aesgh iuhewr iuhiuher uhbuirsdfg iuhuierhf aesgh iuhewr iuhiuhe==261", _
        "==jfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowerer hkjfgsjkerfg iouhwuioerg iuoohuiosdrg iuohiuoh uiowere==787")
      For j = LBound(find) To UBound(find)
        ' the solution code is below this line
        Set r = wDoc.Content
        i = 2 ' repetitions to f&r
        While r.find.Execute(FindText:=find(j)) And i > 0
          r.Text = repl(j)
          i = i - 1
          r.End = wDoc.Content.End
        Wend
        ' the solution code is above this line
      Next
    End Sub
    

    enter image description here