且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 VBA for Word 中查找/替换字符限制解决方法

更新时间:2022-11-28 10:11:45

要查找过长的文本,请搜索字符串的前 255 个字符,然后将找到的范围扩展到其他字符.OR 将字符串分解为 255 个字符的bites"并连续搜索它们(始终将第一个找到的 Range 扩展到每个后续找到的 Range 的终点).

To find text that's too long, search the first 255 characters of the string, then extend the found Range to the additional characters. OR break down the string into 255-character "bites" and search them in succession (always extending the first found Range to the end point of each succeeding found range).

可以使用太长而无法替换的文本,但不能使用Replace.相反,在循环中将字符串值分配给找到的范围.(注意Wrap需要设置为wdFindStop.) 示例

Using text that's too long for replacement can be done, but not using Replace. Instead, assign the string value to the found range, in a loop. (Note that Wrap needs to be set to wdFindStop.) Example

Dim bFound As Boolean
Dim replacementText as String
Dim findText as String, excessText as String
Dim excessChars as Long, bTooLong as Boolean

findText = "Text to be found..."
If Len(findText) > 255 Then
   bToolLong = True
   excessText = Mid(findText, 256)
   excessChars = Len(excessText)
   findText = Left(findText, 255)
End If
replacementText = "some long string greater than 256 characters"
With Rng.Find
    .Text = findText
    '.Replacement.Text = "" 'replace text won't exceed character limitation'
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
bFound = Rng.Find.Execute
Do While bFound
    If bTooLong Then
      Rng.End = Rng.End + excessChars
      'Possible to check findText against the range
      'If Rng.Text <> findText Then 'do something
    End If
    Rng.Text = replacementText
    Rng.Collapse wdCollapseEnd
    bFound = Rng.Find.Execute
Loop