Automation - replace picture

A

Alan Rohulich

I am using VB.NET to modify a word doc, but am unable to select an existing
picture and replace it with an updated picture. Any help would be greatly
appreciated. To date I can select the picture using the following, but how
do I replace the picture with a new one from my C drive? I have tried
adding a shape, but it ignores the selection and puts the picture at the top
of the document. Thanks in advance.

Regards,
Alan

Sample Code:
oWordapp.Documents.Open("C:\Temp\Report.doc") ' Opens Doc

oWDoc = oWordapp.ActiveDocument() 'Activates
Doc

oWDoc.Content.Find.Execute(FindText:="^g") 'Finds Picture
1st occurrence

oWDoc.Shapes.AddPicture("C:\Temp\Area.jpg") 'Attempts to
replace Picture, but just Adds at top of Doc
 
P

Peter Hewett

Hi Alan

My VB.Net systems not running, so here's the VBA version. Just prefix the
AvtiveDocument and Selection property references with your Word application
object variable name. You'll also need to fix up the wdFindContinue Enum.

Public Sub ReplacePicture()
Dim docWithPic As Word.Document

Set docWithPic = ActiveDocument

With docWithPic.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^g"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
If .Execute Then
Selection.InlineShapes.AddPicture "C:\bath.jpg", False, True
Else
MsgBox "Not Found"
End If
End With
End Sub

The Find is more extensive than in your version, this is really mandatory
as you have to reset the Find objects properties or it will use whatever
setting were last selected by the last user.

HTH + Cheers - Peter
 
A

Alan Rohulich

Hi Peter,

Thanks for the quick reply and solution.... I'll give it a try.....!!!

Regards,
Alan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top