Reputation: 409
I'm trying to create a macro that copies a image into word as an Enhanced Metafile and the resizing it to a specific width.
I have a similar macro in Excel that looks like this:
Sub Macro1()
ActiveSheet.PasteSpecial Format:="Picture (Enhanced Metafile)", Link:=False _
, DisplayAsIcon:=False
Selection.ShapeRange.Width = 255
End Sub
This was simply recorded in Excel and works like a charm. However, it seems impossible to do the same thing in word.
If I don't use record a macro I'll just paste the picture and shift+left arrow to select the picture. But as soon as I start recording this doesn't work. I've looked around and apparantly it has to do with Inlineshapes? But I can't find a piece of code that actually allows me to select the picture I just pasted in, for me to resize afterwards.
Why is this made this way and how do I fix it?
Upvotes: 3
Views: 2740
Reputation: 25693
When you paste in Word using VBA the pasted content is not selected, apparently that's different in Excel. Perhaps because the Shape is linked to a workbook cell and the cell is selected?
In any case, the following code successfully picks up the pasted image for further manipulation. What it does is count the number of InlineShapes from the beginning of the document to the current selection, plus one character.
After the paste action the new InlineShape will have been added to the number of items in the range, so it can be picked up by its index number - (lNrIls + 1)
.
For the sake of completeness I've also included the variation for pasting as a Shape
(meaning the image has text wrap formatting, among other things). The basic approach is the same as for an InlineShape.
Note: By default when an image is pasted Word will use the setting Insert/paste pictures as
from File/Options/Advanced, section "Cut, copy and paste". So on some machines an image might be pasted as an InlineShape and on others as a Shape. If you want to paste specifically inline or with text wrap use PasteSpecial
with the corresponding WdOLEPlacement
enumeration value of either wdFloatOverText
or wdInLine
.
Sub PasteAndSelectPicture()
Dim ils As Word.InlineShape
Dim shp As Word.Shape
Dim lNrIls As Long
Dim lNrShp As Long
Dim rngDoc As Word.Range
Dim rngSel As Word.Range
Set rngDoc = ActiveDocument.content
Set rngSel = Selection.Range
rngDoc.End = rngSel.End + 1
'Get an InlineShape
lNrIls = rngDoc.InlineShapes.Count
rngSel.Paste
Debug.Print rngDoc.InlineShapes.Count, lNrIls
Set ils = rngDoc.InlineShapes(lNrIls + 1)
ils.width = 255
'Get a pasted Shape
' lNrShp = rngDoc.ShapeRange.Count
' rngSel.PasteAndFormat Type:=wdFormatOriginalFormatting
' Debug.Print lNrShp, rngDoc.ShapeRange.Count
' Set shp = rngDoc.ShapeRange(rngDoc.ShapeRange.Count)
' shp.RelativeHorizontalPosition = wdRelativeHorizontalPositionCharacter
' shp.RelativeVerticalPosition = wdRelativeVerticalPositionLine
' shp.Left = 10
' shp.Top = 10
End Sub
Upvotes: 5