Solved

need help with macro that will automatically replace certain words and phrase with a picture

Posted on 2013-06-26
19
452 Views
Last Modified: 2013-06-26
I need to rapidly replace certain word or phrase found in a series of documents with pictures
How would I go about the replace word or phrase with picture part of the macro
0
Comment
Question by:Dov_B
  • 10
  • 6
  • 3
19 Comments
 
LVL 13

Expert Comment

by:Stacy Brown
Comment Utility
You can use the advanced find dialog to do this.  You process will just need a tiny bit of setup.

Part 1 - Prep the Picture

Insert your picture into a blank Word Document
Save it for good measure
Select the picture
COPY

Part 2 - Advanced find
Open up the document you need to modify
Click the down arrow next to Find on the Home ribbon
Choose Advanced Find
Click the REPLACE Tab
Click on the Find line and type the word/phrase you want to replace
Click on the REPLACE line
Click the MORE button if necessary
Click the Special button
Select Clipboard Contents
This should place a ^c on the Replace line
Hit REPLACE ALL

That's it you're done!
0
 

Author Comment

by:Dov_B
Comment Utility
how can I turn on the macro recorder and get those steps in vba script
0
 

Author Comment

by:Dov_B
Comment Utility
well it does insert the picture from the clipboard but it puts at the beginning of the lina and not where the word to be replaced was
0
 
LVL 26

Expert Comment

by:MacroShadow
Comment Utility
Are you dealing with one picture?
0
 

Author Comment

by:Dov_B
Comment Utility
B"H your here just in time!
No I am going to have a whole series of icons that replace a whole series of words in zillions of docs
0
 
LVL 26

Expert Comment

by:MacroShadow
Comment Utility
Is replacing one at a time acceptable?
0
 

Author Comment

by:Dov_B
Comment Utility
yes
0
 
LVL 26

Accepted Solution

by:
MacroShadow earned 300 total points
Comment Utility
In which case the following should work:
Option Explicit

Sub ProcessAll(strPath As String, strTxtToReplace As String, strImgPath As String)
    Dim WdDoc As Document, strFile As String

    strFile = Dir(strPath & "*.docx")
    'Loop through all .docx files in that path
    Do While strFile <> ""
        Set WdDoc = Application.Documents.Open(strPath & strFile)

        'Do your Search/Replace
        ReplaceTextWithImage strTxtToReplace, strImgPath
        
        'Save it
        WdDoc.Close wdSaveChanges
        strFile = Dir
    Loop
End Sub

Public Sub ReplaceTextWithImage(strTextToReplace As String, strImagePath As String)
  
    Application.ScreenUpdating = False
    With Selection
        .HomeKey Unit:=wdStory

        With .Find
            .ClearFormatting
            .Text = strTextToReplace
            ' Loop until Word can no longer
            ' find the search string, inserting the specified image at each location
            Do While .Execute
                Selection.MoveRight
                Selection.InlineShapes.AddPicture FileName:=strImagePath, LinkToFile:=False, SaveWithDocument:=True
            Loop
        End With
    End With

    'Delete the original text
    With Selection.Find
        .ClearFormatting
        .Text = strTextToReplace
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

    Application.ScreenUpdating = True

End Sub

Open in new window


Call it using the necessary parameters. i.e.
ProcessAll "C:\", "Whatever", "C:\Test\icon.jpg"

Open in new window

0
 
LVL 13

Assisted Solution

by:Stacy Brown
Stacy Brown earned 200 total points
Comment Utility
if you do actually want VBA code.  This will do basically what I listed above.  You will need to do a couple things in order for this code to work

Create a word document that contains just the picture you wish to replace words with
Save it locally

Open your find/replace document.  Make sure this is the first document you open

Here is the code:

Sub ComboInsertPicReplaceWordWithPicCode()

Dim strPicFileName As String
Dim Message, Title, Default, MyValue

'Get the path to the file with the picture in it

Message = "What is the full path to the document containing the picture?"    ' Set prompt.
Title = "Picture File Name"    ' Set title.
Default = "C:\Users\[username]\Documents\PicDoc.docx"    ' Set default.
' Display message, title, and default value.
strPicFileName = InputBox(Message, Title, Default)

'Open the file with the picture in it.
'IMPORTANT:  The picture must be the only thing inserted in this file and must be inserted at thevery beginning of the file.
'There should only be one line (paragraph) in the document

Documents.Open FileName:=strPicFileName, ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
        PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:=""
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    
    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    Selection.Copy

Windows(1).Activate

Selection.HomeKey Unit:=wdStory
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "dolor" 'replace this with the text you want to find
        .Replacement.Text = "^c"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Selection.HomeKey Unit:=wdStory
End Sub

Open in new window

0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 13

Expert Comment

by:Stacy Brown
Comment Utility
Wow...sorry folks...looks like I missed a bunch of the conversation.
0
 

Author Comment

by:Dov_B
Comment Utility
Dear MacroShadow,
This has happened to me before when using inline shapes it errored out attached is a screan shot with the error what it says is

Run-time error '-2147467259(80004005)':
Method 'AddPicture' of object 'InlineShapes' failed
6-26-2013-2-37-03-PM.png
0
 

Author Comment

by:Dov_B
Comment Utility
ok I fixed it with this
ActiveDocument.SetCompatibilityMode wdWord2007
but still it just stuck the pictures in the begiining of the doc not where the word to be replaced was found
0
 

Author Comment

by:Dov_B
Comment Utility
waqit no that did not fix it
0
 
LVL 26

Expert Comment

by:MacroShadow
Comment Utility
Can you please upload the document, I just tried it again (Word 2010) and it works fine.
0
 

Author Comment

by:Dov_B
Comment Utility
0
 
LVL 26

Expert Comment

by:MacroShadow
Comment Utility
Worked fine by me, see attached, guess which word was replaced.
THE-AVOS-NEZIKIN.zip
0
 

Author Comment

by:Dov_B
Comment Utility
there is nothing in the zip! Sorry but if possible please resend. Thanks!
0
 
LVL 26

Expert Comment

by:MacroShadow
Comment Utility
There is something weird with your computer, I just downloaded the zip and it contains the THE-AVOS-NEZIKIN.docm file.

Anyway, here it is again.
THE-AVOS-NEZIKIN.zip
0
 

Author Comment

by:Dov_B
Comment Utility
ok I unzipped it with a different unzipping program and the word is toldah Nice pic! but here is the "zach" number one dont u know no loshon hura is permitted so please dont call my computer names. 2nd of its all I got what do I do about that blessed (I practice what I preach) error any ideas on that. In any event I will award you all most of the points and post that as a speerate issue. Thanks for that macro its a work of art! May you be blessed again and again the zechus ot the tinokos shel bais raban is with you!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

There is a feature provided by MS Word that lets you create an Table of Contents for your Word document automatically. To use this feature for other documents there are two steps involved,   1.  Prepare your document for a table of contents (he…
Nice table. Huge mess. Maybe this was something you created way back before you figured out tabs or a document you received from someone else. Either way, using the spacebar to separate the columns resulted in a mess. Trying to convert text to t…
The viewer will learn how to make their project stand out over others by learning how to change colors and shapes, add spaces, change directions, and add bullets to their charts.
In a previous video Micro Tutorial here at Experts Exchange (http://www.experts-exchange.com/videos/1358/How-to-get-a-free-trial-of-Office-365-with-the-Office-2016-desktop-applications.html), I explained how to get a free, one-month trial of Office …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now