Share via

MS Word VBA string question

Anonymous
2019-06-18T17:03:01+00:00

Some VBA code that works:

Public Function S_And_R(ByVal rngStory As Word.Range, ByVal strSearch As String, ByVal strReplace As String) As Boolean

  With rngStory.Find

    .ClearFormatting

    .Replacement.ClearFormatting

    .Text = strSearch

    .Replacement.Text = strReplace

    .Wrap = wdFindContinue

    '.Execute Replace:=wdReplaceAll

  End With

  S_And_R = rngStory.Find.Execute(Replace:=wdReplaceAll)

End Function

The function works fine unless strReplace is more than 254 characters.  I get no error message, nothing, it just doesnt make the replacement.  strReplace actually has the value greater than 255 char, so its not a problem passing the value into the function, its in the actual replace action. 

This indicates that replacement.text is a string and this indicates that a string should be able to handle some huge number of characters, far beyond what I need.  What am I doing wrong?

I need to be able to handle more than 255 characters.  Any suggestions?

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Paul Edstein 82,861 Reputation points Volunteer Moderator
2019-06-18T23:11:29+00:00

The Replace expresspion in Find/Replace is limited to 255 characters. For longer strings, you can either put strReplace into the clipboard and use ^c as the Replace expression, or use code like:

Public Function S_And_R(ByVal rngStory As Word.Range, ByVal strSearch As String, ByVal strReplace As String) As Boolean

With rngStory

  With .Find

    .ClearFormatting

    .Replacement.ClearFormatting

    .Text = strSearch

    .Replacement.Text = ""

    .Forward = True

    .Wrap = wdFindStop

    .Execute

  End With

  S_And_R = .Find.Found

  Do While .Find.Found = True

    .Text = strReplace

    .Collapse wdCollapseEnd

    .Find.Execute

  Loop

End With

End Function

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Paul Edstein 82,861 Reputation points Volunteer Moderator
    2019-06-20T12:58:37+00:00

    It 'works' because the replacement text isn't being processed as a replace expression; instead, the code writes the replacement text directly to each found location.

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2019-06-20T12:48:59+00:00

    This works, and it has solved my problem.  I would like to understand *why* this works....but for the moment, I accept that it does.

    Thanks again.  Where is your tip jar?

    Was this answer helpful?

    0 comments No comments