0
votes

I have a document that creates a template page from a VBA script every time I need to insert a specific item into my document, its a great time saver, this includes an image. I have got a working foundation whereby it inserts the image and text wraps it where I want it to be, however the file path is an absolute one. I would like the file path to specify that the image file is within the same directory as the active document so that if I move the directory to a different location this macro will not be broken.

The problem is a little beyond my vba skills, I have worked out I should probably use the ActiveDocument.Path command but I am not sure how to. I appreciate your help. Thank you

Below is my code so far:

Sub Inser_Wrapped_Image()
    Dim shp As Shape
    Set shp = ActiveDocument.Shapes.AddPicture( _
        FileName:="C:\Users\Edoardo\Documents\My Work\PhD\SkyDrive\Tutoring\Houria\Image Replacement.jpg", _
        SaveWithDocument:=True, _
        Anchor:=Selection.Range)
    With shp
        .WrapFormat.Type = wdSquare
        .Left = 246
        .Top = 50
        .Width = 250
        .Height = 188
    End With
End Sub

I have tried writing it as follows but word freezes for a few seconds and then does nothing:

Sub Insert_image()
    Dim shp As Shape
    Set shp = ActiveDocument.Shapes.AddPicture( _
        FileName:=ActiveDocument.Path & "\Image.jpg", _
        SaveWithDocument:=True, _
        Anchor:=Selection.Range)
End Sub
1
That should work. It works on my system. Well you can try the solution I posted and let's hope it works.L42
Edit Hello again, I opened a new document saved it to the same directory and saved that macro (in the document directory in vba - its a .docm) and it still decides to freeze with any of the ThisDocument.Path or ActiveDocument.Path commands resulting in the image not being inserted. Dodgy word install?Fiztban

1 Answers

1
votes

Try this:

Sub Inser_Wrapped_Image()
    Dim shp As Shape
    Dim imgpath As String

    imgpath = ThisDocument.Path
    imgpath = imgpath & "\" & "Image Replacement.jpg"

    Set shp = ThisDocument.Shapes.AddPicture( _
        FileName:=imgpath, SaveWithDocument:=True, _
        Anchor:=Selection.Range)
    With shp
        .WrapFormat.Type = wdWrapSquare
        .Left = 246
        .Top = 50
        .Width = 250
        .Height = 188
    End With
End Sub

I used ThisDocument to explicitly load the picture to the document that contains the macro.
It will work both ways thought if you want to stick to ActiveDocument.