To find and replace a text in the whole document in MS Word 2010 (including tables)

前端 未结 2 831
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 16:03

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
             


        
相关标签:
2条回答
  • 2020-12-03 16:14

    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
    
    0 讨论(0)
  • 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  
    
    0 讨论(0)
提交回复
热议问题