locked
Find & Replace in a Word Document by VB.net

    Question

  • Hi,

    I want to open an existing document, find & replace some words and keep it's format as it is. the following is my code. I will be glade if u pls help me to solve it.

    Dim oWord As Word.Application = CreateObject("Word.Application")
    ' Open word document

    Dim docFile As String = vReportPath & txtInsRptNo.Text & ".doc"

    Dim oDoc As Word.Document = oWord.Documents.Open(docFile)

    Dim oTable1 As Word.Table

    oWord.Visible = True

    ' The Word document may have BUYER_NAME, CUSTOMER_NAME. I will replace them with data which I fetched from oracle database.


    ' Save this word document

    oDoc.SaveAs(docFile, True)

    oDoc.Close()

    oDoc = Nothing

    oWord.Application.Quit()

    oWord = Nothing


    Thanks in advance.

    Sunday, June 01, 2008 7:00 AM

Answers

  • Hi Salim,

    Here is the code sample: Find and Replace within a Word document in VB.NET:

    Imports Word = Microsoft.Office.Interop.Word  
    Public Class Form1  
     
        ' Find / Replace in Word Document  
        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click  
            Dim objWordApp As New Word.Application  
            objWordApp.Visible = True 
     
            'Open an existing document.  
            Dim objDoc As Word.Document = objWordApp.Documents.Open("C:\Trydata\1.doc")  
            objDoc = objWordApp.ActiveDocument  
     
            'Find and replace some text  
            'Replace 'VB' with 'Visual Basic'  
            objDoc.Content.Find.Execute(FindText:="VB", ReplaceWith:="Visual Basic Express", Replace:=Word.WdReplace.wdReplaceAll)  
            While objDoc.Content.Find.Execute(FindText:="  ", Wrap:=Word.WdFindWrap.wdFindContinue)  
                objDoc.Content.Find.Execute(FindText:="  ", ReplaceWith:=" ", Replace:=Word.WdReplace.wdReplaceAll, Wrap:=Word.WdFindWrap.wdFindContinue)  
            End While 
     
            'Save and close the document  
            objDoc.Save()  
            objDoc.Close()  
            objDoc = Nothing 
            objWordApp.Quit()  
            objWordApp = Nothing 
     
        End Sub 
    End Class 
     

    In addition. there is ong good document including demo project, code sample and detailed instruction.
    http://www.codeproject.com/KB/cs/Word_Automation.aspx





    Best regards,
    Martin Xie
    Thursday, June 05, 2008 10:00 AM

All replies

  • Hi Salim,

    Here is the code sample: Find and Replace within a Word document in VB.NET:

    Imports Word = Microsoft.Office.Interop.Word  
    Public Class Form1  
     
        ' Find / Replace in Word Document  
        Private Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click  
            Dim objWordApp As New Word.Application  
            objWordApp.Visible = True 
     
            'Open an existing document.  
            Dim objDoc As Word.Document = objWordApp.Documents.Open("C:\Trydata\1.doc")  
            objDoc = objWordApp.ActiveDocument  
     
            'Find and replace some text  
            'Replace 'VB' with 'Visual Basic'  
            objDoc.Content.Find.Execute(FindText:="VB", ReplaceWith:="Visual Basic Express", Replace:=Word.WdReplace.wdReplaceAll)  
            While objDoc.Content.Find.Execute(FindText:="  ", Wrap:=Word.WdFindWrap.wdFindContinue)  
                objDoc.Content.Find.Execute(FindText:="  ", ReplaceWith:=" ", Replace:=Word.WdReplace.wdReplaceAll, Wrap:=Word.WdFindWrap.wdFindContinue)  
            End While 
     
            'Save and close the document  
            objDoc.Save()  
            objDoc.Close()  
            objDoc = Nothing 
            objWordApp.Quit()  
            objWordApp = Nothing 
     
        End Sub 
    End Class 
     

    In addition. there is ong good document including demo project, code sample and detailed instruction.
    http://www.codeproject.com/KB/cs/Word_Automation.aspx





    Best regards,
    Martin Xie
    Thursday, June 05, 2008 10:00 AM
  • Thanks Martin.

    Your code is very nice & usefull.

    Thanks again.
    Salim
    Saturday, June 07, 2008 5:42 AM
  • Hi, I tried the code but there was an error when it was being executed

    The stub received bad data. (Exception from HRESULT: 0x800706F7)

    Need help!
    Tuesday, July 29, 2008 2:59 AM
  • I had the same error.  Would appreciate some help.
    Monday, November 09, 2009 6:13 PM
  • Okay, so I found the answer to that exception it was throwing and decided to post the solution here in case anyone comes across this thread and needs it.

    Apparently there is a thing called 'late binding', which means that you dim objects first and then assign interop identities to them later. See the code example below. Apparently, there is a bug that causes an exception to be thrown if 'early binding' is used, i.e. you immediately dim an object and assign it to equal a Word.Documnet or something. 

    So this is early binding and causes the exception:

    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2. Dim oWord As Word.Application   'Assign oWord to be a Word Application
    3. Dim oDoc As Word.Document       'Assign oDoc to be a Word Document
    4. 'Start Word and open the document template.
    5.         Dim Range As Word.Range
    6.  Range.Text = "Figure* Figure* See attached for my comments and markups. Thank you for your cooperation. Figure* Figure*"
    7.  
    8.         With oWord.Selection.Find
    9.             .Text = "Figure*"
    10.             .Replacement.Text = "Figure 1"
    11.             .Forward = True
    12.             .Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
    13.             .Format = False
    14.             .MatchCase = False
    15.             .MatchWholeWord = False
    16.             .MatchWildcards = False
    17.             .MatchSoundsLike = False
    18.             .MatchAllWordForms = False
    19.         End With
    20.         oWord.Selection.Find.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
    21. End Sub

    This is late binding and magically runs exception free:

    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.        
    3.         Dim oWord As Object
    4.         Dim oDoc As Object
    5.         Dim range As Object
    6.  
    7.         oWord = CreateObject("Word.Application")
    8.         oWord.Visible = True
    9.         oDoc = oWord.Documents.Add
    10.         Range = oDoc.Content
    11.         range.Text = "Figure* Figure* See attached for my comments and markups. Thank you for your cooperation. Figure* Figure*"
    12.  
    13.         With oWord.Selection.Find
    14.             .Text = "Figure*"
    15.             .Replacement.Text = "Figure 1"
    16.             .Forward = True
    17.             .Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
    18.             .Format = False
    19.             .MatchCase = False
    20.             .MatchWholeWord = False
    21.             .MatchWildcards = False
    22.             .MatchSoundsLike = False
    23.             .MatchAllWordForms = False
    24.         End With
    25.         oWord.Selection.Find.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
    26.  
    27.     End Sub

    I hope this gets found by others that are experiencing the same problem I was. Just a warning, I seem to lose intellisense when I do the late binding--an unfortunate side effect, but the code runs. Good luck! 
    Monday, November 16, 2009 5:43 PM
  • I suggest to use a c# word component Spire.Doc, I use it long time, quit good.
    It supports find & replace some words .
    May help to you.

    http://www.e-iceblue.com/Introduce/word-for-net-introduce.html

    Tuesday, August 10, 2010 6:43 AM
  • LA SOLUCION: THE SOLUTION

    Yo encontre el problema my dear  GrimstoneX  (I have the solution and the best form)

    Tuve un problema con el word y despues de tanto problema y de tanto buscar por la web y probar un monton de combinaciones y hacer las variantes posible di con la solucion  y encontre el ¿POR QUE? del problema que tu llamas "early binding" o enlace prematuro.Realmente no se trata de enlaces ni de cosas por el estilo.

    Sucede que al parecer despues de cierta version del Office (2003, 2007, etc), la clase "Microsoft.Office.Interop.Word.Document" no tiene o no implementa cierta interfaz que genera "Microsoft.Office.Interop.Word.Application.Documents.Open" o "Microsoft.Office.Interop.Word.Application.Documents.Add".

    Por ese motivo el metodo "Execute" de "Microsoft.Office.Interop.Word.Application.Documents.Open(,,,,,).Content.Find.Execute" proviene de otra implementacion diferente a "Microsoft.Office.Interop.Word.Document.Content.Find.Execute"

    De la misma manera. "Microsoft.Office.Interop.Word.Application.Documents.Add().Content.Find.Execute" proviene de otra implementacion diferente a "Microsoft.Office.Interop.Word.Document.Content.Find.Execute"

    Por ello lo unico que deberiamos cambiar en nuestra implementacion es la declaracion "Dim wordDoc As Microsoft.Office.Interop.Word.Document" por "Dim wordDoc As Object"

    El tipo "Object" soportará la instancia arrojada por "Documents.Open" o "Documents.Open.Add" y las llamadas a sus metodos y propiedades funcionaran. Pero con el tipo "Word.Document" se tendrá alguna clase de error debido a las implementaciones distintas (Yo desconozco exactamente cuales son estas diferencias, pero existen).

    De esta manera el codigo ideal seria asi:

        Public Shared Sub ReemplazarTextoEnWord(ByVal _filename As String, ByVal texto As String, ByVal textoNuevo As String)
            Dim miss As Object = System.Reflection.Missing.Value
            Dim wordApp As New Word.Application
            Dim wordDoc As Object = wordApp.Documents.Open(_filename, False, False, False, miss, miss, miss, miss) 'Recomendada,funciona muy bien
            'Dim wordDoc As Word.Document = wordApp.Documents.Open(_filename, False, False, False, miss, miss, miss, miss) 'NO Recomendada,arrojara error en metodos y propiedades
    
            Try
                wordDoc.Content.Find.Execute(FindText:=texto, ReplaceWith:=textoNuevo, Replace:=Word.WdReplace.wdReplaceAll)
                wordDoc.Save()
            Catch ex As Exception
                Utiles.ManejarExcepcion(ex)
            Finally
                wordDoc.Close()
                wordDoc = Nothing
                wordApp.Quit()
                wordApp = Nothing
            End Try
        End Sub
    

    Ya lo he probado varias veces y esto funciona muy bien. Saludos espero sea util a quien lo lea

    Wednesday, October 31, 2012 6:05 PM
  • The following two posts present the details to find/highlight and replace text in Word. Maybe you can get some suggestions from them.

    http://janewdaisy.wordpress.com/2012/02/23/how-to-find-and-highlight-specified-words-in-ms-word-cvb-net/

    http://janewdaisy.wordpress.com/2012/02/24/how-to-replace-words-in-ms-word-document-cvb-net/

    Friday, November 09, 2012 4:01 AM