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

时间:2018-11-05 12:19:22

标签: vba ms-word

我有一个基本的vbscript,可以在Microsoft Word中查找和替换,但是我不能遍历一定数量的字符(我认为是256)。我想知道是否有人对这个问题有解决办法。以下是我正在使用的脚本示例:

Sub FixedReplacements()
Dim Rng As Range
Dim SearchString As String
Dim EndString As String
Dim Id As String
Dim Link As String

Rng.Find.ClearFormatting
Rng.Find.Replacement.ClearFormatting
With Rng.Find
    .Text = "" 'find text won't exceed character limitation'
    .Replacement.Text = "" 'replace text won't exceed character limitation'
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Rng.Find.Execute Replace:=wdReplaceAll   

3 个答案:

答案 0 :(得分:0)

Find().Text中没有限制。检查一下:

Option Explicit

Sub TestMe()

    Dim myRange As Range
    Set myRange = ActiveDocument.Content

    Dim lookFor As String
    lookFor = "The text to be searched for. Use an empty string () to search for formatting only. You can search for special characters by specifying appropriate character codes. For example, corresponds to a paragraph mark and corresponds to a tab character."
    myRange.Find.Execute FindText:=lookFor, ReplaceWith:="hello", Replace:=wdReplaceAll

End Sub

可能的限制部分是一条线,该线在要查找的字符串中没有正确解析,因此找不到。

答案 1 :(得分:0)

要查找太长的文本,请搜索字符串的前255个字符,然后将找到的范围扩展到其他字符。或将字符串分解为255个字符的“位”,并依次搜索(始终将找到的第一个Range扩展到每个后续找到的范围的终点)。

可以使用太长的文本进行替换,但不能使用Replace。而是循环将字符串值分配给找到的范围。 (请注意,Wrap必须设置为wdFindStop。)示例

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

答案 2 :(得分:-1)

我花了很长时间寻找一个简单的解决方案;为了那些也拖网渔船的利益,请考虑我的解决方案。

我的假设是有一次要替换的文本。

  1. 查找要替换的文本
  2. 在之后插入新文本
  3. 使用查找和替换,删除找到的文本

    With WordDoc.Content
    .Find.Execute findText:="text", Forward:=True, Wrap:=wdFindStop
    .InsertAfter Text:="newtext"
    .Find.Execute findText:="text", ReplaceWith:=""
    End With
    
相关问题