user1783736
user1783736

Reputation: 249

Microsoft Word Macro VBA Replace text with image in document header

I have the following VBA code that finds the placeholder text (FindText) in all active documents and replaces the text with an image. This code works fine when the text is in the document body; However, if the placeholder text is in the document header, the text does not get replaced with the image.

My question is, How do I replace the placeholder text with the image if the text is in the header of the document?

Sub InsertImagesAllDocuments()

Dim n, c As Integer
n = Application.Documents.Count
c = 1

Dim r As range

Windows(c).Activate


Do
Dim imageFullPath As String
Dim FindText As String
imageFullPath = "C:\Logo.jpg"
FindText = "TextPlaceholder"
    With Selection
    .HomeKey Unit:=wdStory

    With .Find
        .ClearFormatting
        .text = FindText
        ' 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:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True
        Loop

    End With
End With


    c = c + 1

    On Error Resume Next
    Windows(c).Activate

Loop Until c > n



 End Sub

Upvotes: 0

Views: 8416

Answers (1)

Sorceri
Sorceri

Reputation: 8033

you will want to open the header in order to replace the text. You can do so with this line of code

ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
'now the header is accessible, run your code
   With Selection
    .HomeKey Unit:=wdStory

        With .Find
        .ClearFormatting
        .text = FindText
        ' 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:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True
        Loop

    End With
End With

Upvotes: 2

Related Questions