8

我有一个包含表格的 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

这可以很好地替换我在表格之外的所有内容。但它不会替换表中的任何内容。

4

2 回答 2

18

如果您的目标是在整个文档中执行替换(从代码中看起来是这样,但并不明确),我建议您使用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
于 2013-09-04T10:47:45.417 回答
8

我使用了以下代码,对于文档中的所有事件,它都像魅力一样工作......

  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  
于 2014-01-30T06:59:36.980 回答