none
How to ReplaceAll text in Word RRS feed

Answers

  • Assuming you are within the context of a Microsoft.Interop.Word.Document:

        Public Sub GlobalReplaceAll(findText As String, replaceText As String, matchCase As Boolean, matchWord As Boolean)
            Dim doReplace = New Action(Of Word.Find)(Sub(find As Word.Find)
                                                         find.Execute(findText, matchCase, matchWord, False, False, False, True, Word.WdFindWrap.wdFindContinue, False, replaceText, Word.WdReplace.wdReplaceAll)
                                                     End Sub)
            For Each section As Word.Section In Me.Sections
                For Each header As Word.HeaderFooter In section.Headers
                    doReplace(header.Range.Find)
                Next
                For Each footer As Word.HeaderFooter In section.Footers
                    doReplace(footer.Range.Find)
                Next
                doReplace(section.Range.Find)
            Next
        End Sub


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Monday, May 23, 2016 10:09 PM

All replies

  • What version of MSWord are you handling?

    What version of VB?

    Do you have code already to open the .doc file?

    'cause the docx could be handled a bit differently than the .doc

    Monday, May 23, 2016 7:50 PM
  • Assuming you are within the context of a Microsoft.Interop.Word.Document:

        Public Sub GlobalReplaceAll(findText As String, replaceText As String, matchCase As Boolean, matchWord As Boolean)
            Dim doReplace = New Action(Of Word.Find)(Sub(find As Word.Find)
                                                         find.Execute(findText, matchCase, matchWord, False, False, False, True, Word.WdFindWrap.wdFindContinue, False, replaceText, Word.WdReplace.wdReplaceAll)
                                                     End Sub)
            For Each section As Word.Section In Me.Sections
                For Each header As Word.HeaderFooter In section.Headers
                    doReplace(header.Range.Find)
                Next
                For Each footer As Word.HeaderFooter In section.Footers
                    doReplace(footer.Range.Find)
                Next
                doReplace(section.Range.Find)
            Next
        End Sub


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Monday, May 23, 2016 10:09 PM
  • I refered this msdn example: Find and Replace Text in Word with C#  and replaced the text in both body and header successfully(have not check footer), you can give it a try:

    Dim document As New Document()
    document.LoadFromFile("E:\FileName.docx")
    document.Replace("string", "new string", False, True)
    document.SaveToFile("filename.docx", FileFormat.Docx)

    Tuesday, May 24, 2016 4:30 AM