VB.NET Search and Replace in Word document

By Allen Stoner

Sometimes it may be necessary to use a VB.NET applicaiton to do a Search and Replace in a MS Word document. This function does the search and replace in all sections of the Word document and saves it back to the disk with the same name.

Imports Microsoft.Office.Interop.Word

  Const wdReplaceAll = 2
  Const wdFindStop = 0
  Const wdFindContinue = 1
  Const wdNoProtection = -1

  Private Function SearchReplaceInFile(ByRef SearchFor As String, ByRef ReplaceWith As String, ByRef strFileName As String) As Boolean
    Dim docProtectType As Int16
    Dim MadeChange As Boolean = False
    Dim DestFileName As String = ""
    Dim appWord As Application
    Dim wrdDoc As Document

    appWord = New Application
    wrdDoc = appWord.Documents.Open(strFileName)
    ' Save the protection type of the document then turn off protection
    docProtectType = wrdDoc.ProtectionType
     If docProtectType <> wdNoProtection Then
     End If

    Dim oRange As Microsoft.Office.Interop.Word.Range
    ' Search and replace in ALL parts of the Word document, header, body and footer
    For Each oRange In wrdDoc.StoryRanges
      With oRange.Find
        .MatchCase = False
        .MatchPhrase = True
        .Text = SearchFor
        .Replacement.Text = ReplaceWith
        If .Execute(Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue) Then
          MadeChange = True
          MadeChange = False
        End If
      End With

    ' Put protection back the way it was
    wrdDoc.Protect(Type:=docProtectType, NoReset:=True)
    wrdDoc = Nothing
    appWord = Nothing
    Return MadeChange
  End Function

VB.NET Search and Replace in Word document  (4492 Views)