1
votes

I am creating an automated document generation tool using data from an Excel workbook through VBA code.

The code below replaces text and inserts the images, however, they get pushed into the top of the document.

Is there any way to return the position of the found text, declare a range based on the position, and use that to insert the inline-shape (image) into the line after the tagName text?

I had this working previously through calling Word macros from Excel, however, this needs to be completely Excel based.
This program will be handling Word documents that have no VBA.

For Each sr2 In wDoc.StoryRanges
    With sr2.Find
        .Text = tagName
        .Replacement.Text = tagValue
        .Wrap = 1
        .Execute Replace:=2
        If .Found = True Then
            sr2.InlineShapes.AddPicture fileName:=ThisWorkbook.Path & "\1. SOW Templates\ Client Summary import.jpg"
        End If
    End With
Next sr2
1

1 Answers

0
votes

To easily loop through the results of the Find method, it would be easier if you are using Replace:=wdReplaceOne (wdReplaceOne=1) instead of Replace:=wdReplaceAll (wdReplaceAll=2). (Based on this this answer).

To insert the image, I would suggest you to select the range you want the image to be. Add it as a free floating image and then convert it to an inline shape.

Here's a way to do this:

Dim r As Object 'Word.Range
Dim bFound As Boolean

bFound = True
Set r = wDoc.Content

r.Find.ClearFormatting
Do While bFound
    With r.Find
        .Text = tagname
        .Replacement.Text = tagValue
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        bFound = .Execute(Replace:=wdReplaceOne)
    End With

    If bFound Then
        r.Select
        Selection.Next(Unit:=wdParagraph, Count:=1).Select
        Dim img As Object 'Word.Shape
        Set img = wDoc.Shapes.AddPicture(Filename:=ThisWorkbook.Path & "\1. SOW Templates\ Client Summary import.jpg")
        img.ConvertToInlineShape
    End If
Loop