10

I have an MS Word document including a table. I am trying to find and replace text via VBA using the following code:

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

This works fine for replacing all my content which is outside of the table. But it will not replace any of the content within the table.

kvantour
  • 25,269
  • 4
  • 47
  • 72
122user321
  • 221
  • 1
  • 4
  • 13

2 Answers2

19

If your goal is to perform replacements in the whole documents (it looks so from the code, but it is not explicit), I would suggest you use Document.Range instead of the Selection object. Using Document.Range will make sure everything is replaced, even inside tables.

Also, it is more transparent to the user, as the cursor (or selection) is not moved by the macro.

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
d-stroyer
  • 2,638
  • 2
  • 19
  • 31
8

I have used the following code and it works like charm..... for all the occurances that are found in the document.

  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  
Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
122user321
  • 221
  • 1
  • 4
  • 13