Visual Basic Development Bookmark and Share   
 Home > Visual Basic IDE > Find & Replace in a Word Document by VB.net
 

Find & Replace in a Word Document by VB.net

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 documentmay 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.

Salim_Ahammed  Sunday, June 01, 2008 7:00 AM
Hi Salim,

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

ImportsWord=Microsoft.Office.Interop.Word
PublicClassForm1
'Find/ReplaceinWordDocument
PrivateSubButton1_Click(ByValsenderAsSystem.Object,ByValeAsSystem.EventArgs)HandlesButton1.Click
DimobjWordAppAsNewWord.Application
objWordApp.Visible=True
'Openanexistingdocument.
DimobjDocAsWord.Document=objWordApp.Documents.Open("C:\Trydata\1.doc")
objDoc=objWordApp.ActiveDocument
'Findandreplacesometext
'Replace'VB'with'VisualBasic'
objDoc.Content.Find.Execute(FindText:="VB",ReplaceWith:="VisualBasicExpress",Replace:=Word.WdReplace.wdReplaceAll)
WhileobjDoc.Content.Find.Execute(FindText:="",Wrap:=Word.WdFindWrap.wdFindContinue)
objDoc.Content.Find.Execute(FindText:="",ReplaceWith:="",Replace:=Word.WdReplace.wdReplaceAll,Wrap:=Word.WdFindWrap.wdFindContinue)
EndWhile
'Saveandclosethedocument
objDoc.Save()
objDoc.Close()
objDoc=Nothing
objWordApp.Quit()
objWordApp=Nothing
EndSub
EndClass

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





Best regards,
Martin Xie
Martin Xie - MSFT  Thursday, June 05, 2008 10:00 AM
Hi Salim,

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

ImportsWord=Microsoft.Office.Interop.Word
PublicClassForm1
'Find/ReplaceinWordDocument
PrivateSubButton1_Click(ByValsenderAsSystem.Object,ByValeAsSystem.EventArgs)HandlesButton1.Click
DimobjWordAppAsNewWord.Application
objWordApp.Visible=True
'Openanexistingdocument.
DimobjDocAsWord.Document=objWordApp.Documents.Open("C:\Trydata\1.doc")
objDoc=objWordApp.ActiveDocument
'Findandreplacesometext
'Replace'VB'with'VisualBasic'
objDoc.Content.Find.Execute(FindText:="VB",ReplaceWith:="VisualBasicExpress",Replace:=Word.WdReplace.wdReplaceAll)
WhileobjDoc.Content.Find.Execute(FindText:="",Wrap:=Word.WdFindWrap.wdFindContinue)
objDoc.Content.Find.Execute(FindText:="",ReplaceWith:="",Replace:=Word.WdReplace.wdReplaceAll,Wrap:=Word.WdFindWrap.wdFindContinue)
EndWhile
'Saveandclosethedocument
objDoc.Save()
objDoc.Close()
objDoc=Nothing
objWordApp.Quit()
objWordApp=Nothing
EndSub
EndClass

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





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

Your code is very nice & usefull.

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

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

Need help!
aspsb  Tuesday, July 29, 2008 2:59 AM
I had the same error. Would appreciate some help.
GrimstoneX  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. With oWord.Selection.Find
  8. .Text = "Figure*"
  9. .Replacement.Text = "Figure 1"
  10. .Forward = True
  11. .Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
  12. .Format = False
  13. .MatchCase = False
  14. .MatchWholeWord = False
  15. .MatchWildcards = False
  16. .MatchSoundsLike = False
  17. .MatchAllWordForms = False
  18. End With
  19. oWord.Selection.Find.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
  20. 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. Dim oWord As Object
  3. Dim oDoc As Object
  4. Dim range As Object
  5. oWord = CreateObject("Word.Application")
  6. oWord.Visible = True
  7. oDoc = oWord.Documents.Add
  8. Range = oDoc.Content
  9. range.Text = "Figure* Figure* See attached for my comments and markups. Thank you for your cooperation. Figure* Figure*"
  10. With oWord.Selection.Find
  11. .Text = "Figure*"
  12. .Replacement.Text = "Figure 1"
  13. .Forward = True
  14. .Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
  15. .Format = False
  16. .MatchCase = False
  17. .MatchWholeWord = False
  18. .MatchWildcards = False
  19. .MatchSoundsLike = False
  20. .MatchAllWordForms = False
  21. End With
  22. oWord.Selection.Find.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
  23. 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!
GrimstoneX  Monday, November 16, 2009 5:43 PM

You can use google to search for other answers

Custom Search

More Threads

• What is the best way to reversed deploy through ClickOnce
• VB2005 Icons for Binding Navigator
• Harddrive interaction
• create a dataset, and drag and drop the default datagrid on from
• Visual Basic 6 and Crystal Reports 9 SQL Query Issue
• Can ClickOnce Help Me Resolve This issue?
• Posting Multiple Dates at one time
• visual basic ide+compiler is a mess!
• WS_THICKFRAME (user32.dll) doesn't work with new process
• Configure Data Source Wizard only detects parameters in SELECT query