在MS Word 2010中查找和替换整个文档中的文本(包括表格)

122*_*321 7 vba ms-word

我有一个MS Word文档,包括一个表.我试图使用以下代码通过VBA查找和替换文本:

If TextBox1.Text <> "" Then
    Options.DefaultHighlightColorIndex = wdNoHighlight
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Highlight = True
    With Selection.Find
        .Text = "<Customer_Name>"
        .Replacement.Text = TextBox1.Text
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

Selection.Find.ClearFormatting
    With Selection.Find.Font
    .Italic = True
    End With
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find.Replacement.Font
    .Italic = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    End If
Run Code Online (Sandbox Code Playgroud)

这适用于替换表格之外的所有内容.但它不会取代表中的任何内容.

d-s*_*yer 15

如果您的目标是在整个文档中执行替换(从代码看起来如此,但它没有明确),我建议您使用Document.Range而不是Selection对象.使用Document.Range将确保所有内容都被替换,甚至在表格内.

此外,它对用户更透明,因为宏不移动光标(或选择).

Sub Test()
  If TextBox1.Text <> "" Then
    Options.DefaultHighlightColorIndex = wdNoHighlight
    With ActiveDocument.Range.Find
      .Text = "<Customer_Name>"
      .Replacement.Text = TextBox1.Text
      .Replacement.ClearFormatting
      .Replacement.Font.Italic = False
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      .Execute Replace:=wdReplaceAll
    End With
  End If
End Sub
Run Code Online (Sandbox Code Playgroud)


122*_*321 7

我已经使用了以下代码,它就像魅力一样.....对于文档中发现的所有事件.

  stringReplaced = stringReplaced + "string to be searched"
For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "string to be searched"
        .Replacement.Text = "string to be replaced"
        .Wrap = wdFindContinue
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Highlight = False
        .Execute Replace:=wdReplaceAll
    End With
Next myStoryRange  
Run Code Online (Sandbox Code Playgroud)