Question

I am making a VBA script to generate default pages for my template document, it is all going well except for when I try to insert an image that is right aligned and text wrapped. I used VBA many years ago only for excel so am not sure how to structure the VBA script. I started making the VBA script for the image by itself to be later integrated which you can find below.

What I want to achieve with the VBA script

  • For it to insert an image from a file within the same directory as the template file (do I have to put the full path or can I put a truncated one to specify that it will always be in the same directory?)
  • For the inserted image to be square text wrapped (default distances)
  • For the image to be aligned with the left margin relative to the line I have inserted it in
  • The height of the image is at 200 x 150

Would you kindly be able to help elaborate on the MWE I have below. Thank you:

Sub Insert_picture()
'
' Insert_picture Macro
'

    Dim imagePath As String
    imagePath = "C:\Users\Edoardo\Documents\My Work\PhD\SkyDrive\Tutoring\Houria\Image Replacement.jpg"

    ActiveDocument.Shapes.AddPicture FileName:=imagePath, _
    LinkToFile:=False, _
    SaveWithDocument:=True, _
    Left:=-5, _
    Top:=5, _
    Anchor:=Selection.Range, _
    Width:=200, _
    Height:=150

    With imagePath
        .WrapFormat.Type = wdWrapSquare
    End With
End Sub
Was it helpful?

Solution

I worked it out in the end as follows:

Sub Insert_SqWrap_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 = wdWrapSquare
        .Left = 246
        .Top = 50
        .Width = 250
        .Height = 188
    End With
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top