Replace a string in a word file

Hi all,

I have word document. I have a particular string in that document. I want to replace that string with another given string using Visual Basic. My original file has some tables and some images which should be modified. I only have to replace a string with another one.

Can you help me out.
If you can provide the source code, it would really help.

It is urgent.

thanks
mrigank
LVL 5
mrigankAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Shahid ThaikaConnect With a Mentor Sole ProprietorCommented:
Create a new Standard EXE project, add two text boxes, a command button and finally set reference to 'Microsoft Word 9.0 Object Library' (or similar. You should have word installed) Copy the code below into your source window. Text1 takes the text to be found and Text2, the word to replace the found text.
I have entered '2' as the parameter for the replace function...
2 = Replace All
0 = Replace None
1 = Replace First






Option Explicit
Private WApp As Word.Application
Private WordD As Word.Document

Private Sub Command1_Click()
Set WApp = New Word.Application
Set WordD = WApp.Documents.Open("C:\My Documents\myfile.doc")

With WApp.Selection.Find
    .Text = Text1
    .ClearFormatting
    .Replacement.ClearFormatting
    .Replacement.Text = Text2
    .Execute Replace:=2
    MsgBox "Done"
End With

If MsgBox("Do you want to save changes?", vbYesNo) = vbYes Then
    WApp.Documents.Close True
Else
    WApp.Documents.Close True
End If
End Sub


Hope this answers your question :).
0
 
Shahid ThaikaSole ProprietorCommented:
I forgot to add the following in the second last line before 'End Sub'

WApp.Quit

But it won't make much difference if you don't include it. You just have to manually close word :).
0
 
Shahid ThaikaSole ProprietorCommented:
Oops, one more mistake found (Silly of me). The code should be 'WApp.Documents.Close True' after the else part of the If statement. Not 'True'.
0
 
Shahid ThaikaSole ProprietorCommented:
Dear mrigank, does the code work or needs any change?
0
All Courses

From novice to tech pro — start learning today.