vbaimagems-wordinsertinline-images

Error when inserting image using variable for Selection.InlineShapes.AddPicture


I am trying to go through a word document, and replace existing image path strings with the actual image. When I enter the address hard coded, it works. But if I put the same code in a variable I get an error

enter image description here

Error:

Run-time error '5152':

This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was typed correctly,
* Select a file from the list of files and folders.

Code:

Sub InsertJPGs()
    For Each singleLine In ActiveDocument.Paragraphs
        Dim Value As Variant
        Dim imageName As String
        Options.DefaultFilePath(wdDocumentsPath) = "d:\Downloads\ReportImages\"
        originalLineText = singleLine.Range.Text
        lineText = singleLine.Range.Text
        If InStr(lineText, ".jpg") <> 0 Then
            singleLine.Range.Select
            rangeText = singleLine.Range.Text
            imageName = rangeText
            imageName = "D:\Downloads\ReportImages\" & rangeText
            'imageName = "D:\Downloads\ReportImages\PictureImportTest_ATTICSkylight#1#_img2.jpg"
            Selection.InlineShapes.AddPicture FileName:= _
                imageName, LinkToFile:=True, SaveWithDocument:=True
        End If
        If InStr(lineText, "[[[IMAGE LIST]]]") <> 0 Then
            Exit For
        End If
    Next singleLine
End Sub

Solution

  • Try:

    Sub Demo()
    Application.ScreenUpdating = False
    Dim FlNm As String: Const StrPath As String = "d:\Downloads\ReportImages\"
    With ActiveDocument.Range
      With .Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "<[! ^t^l^13]@.[Jj][Pp][Gg]>"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchWildcards = True
        .Execute
      End With
      Do While .Find.Found
        FlNm = .Duplicate.Text
        .Text = vbNullString
        .InlineShapes.AddPicture StrPath & FlNm, False, True, .Duplicate
        .Collapse wdCollapseEnd
        .Find.Execute
      Loop
    End With
    Application.ScreenUpdating = True
    End Sub
    

    If you want to retain the filenames in the document, delete or comment out:

    .Text = vbNullString