Pregunta

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
¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top