0

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
djv
  • 15,168
  • 7
  • 48
  • 72
  • Yes it is VBA, my mistake – Celestrial Mar 04 '20 at 21:43
  • Insert `Option Explicit` at the top of your code. Declare all your variables. Avoid the use of Variants. I doubt that VBA will allow you to place your declarations in a loop. Don't `Select` anything. What is `singleline`? A word, a character, a sentence, a paragraph? There are no *lines* in Word, only in what Word displays on the screen. `rangetext` is a derivative of singleline. With `singleline` undefined, what could `rangetext` be? Put a break in your code and check its value before you assign it to the `imagename`. – Variatus Mar 05 '20 at 02:07
  • The most likely source of the error with the OP's code is that 'singleLine.Range.Text' includes a paragraph break - which can't form part of a filename. – macropod Mar 06 '20 at 00:44

1 Answers1

0

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
macropod
  • 12,757
  • 2
  • 9
  • 21