PDA

View Full Version : Word. Insert Image. Resize. Place properly.



inspectorran
09-29-2019, 04:34 PM
I have no experience with VBA but am in need of a fairly simple (I think?) macro to:

1. Place cursor on line.
2. Insert photo from pre-determined filepath.
3. Re-size photo to 2.5" wide (maintain Aspect ratio).
4. Format text-wrapping as "Square".
5. Align photo at right margin (without re-formatting text).
6. Close down and return me to working in the document.

I've searched for quite a while and although there are numerous photo insertion solutions out there, none of them do exactly what I need. I'm sure that tweaking some of the existing solutions would work but since I don't know code I wouldn't know what to change!

Thank you so much in advance for any solution that can be offered.

gmayor
09-29-2019, 09:44 PM
Maybe something like


Sub Macro1()Dim strImage As String
Dim oILShape As InlineShape
Dim oShape As Shape
Dim lngMargin As Long
lngMargin = Selection.Sections(1).PageSetup.RightMargin
strImage = BrowseForFile("Select the image to insert")
Set oILShape = Selection.InlineShapes.AddPicture(strImage)
Set oShape = oILShape.ConvertToShape
With oShape
.LockAspectRatio = msoTrue
.Width = 180
.WrapFormat.Type = wdWrapSquare
.RelativeHorizontalPosition = wdRelativeHorizontalPositionRightMarginArea
.LeftRelative = -(.Width + lngMargin - 10)
End With
End Sub


Private Function BrowseForFile(Optional strTitle As String) As String
'Graham Mayor
Dim fDialog As FileDialog
On Error GoTo Err_Handler
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.TITLE = strTitle
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Image files", "*.png,*.jpg,*.bmp,*.gif,*.tif"
.InitialView = msoFileDialogViewThumbnail
If .Show <> -1 Then GoTo Err_Handler:
BrowseForFile = fDialog.SelectedItems.Item(1)
End With
lbl_Exit:
Exit Function
Err_Handler:
BrowseForFile = vbNullString
Resume lbl_Exit
End Function

Inspect Rand
09-30-2019, 08:08 AM
Thank you Graham!

I feel like such a doofus as I can't even copy and paste that correctly into the template.

I keep getting a "Can't execute code in break mode" message.

Inspect Rand
09-30-2019, 08:26 AM
Ok.

Got it to run.

The picture inserts but at full size, not resized.

Then it brings up the File Explorer window again so I can select another picture. I would just like to shut down so I can continue to work on the document.

I understand I'm asking for free coding here so I understand if this is all that can be offered.

gmayor
09-30-2019, 08:21 PM
I suspect there is a problem with how you have added (or are running) the macro. Apart from the fact the messaging system here has lost a line break in the line


Sub Macro1()Dim strImage As Stringwhich should be
Sub Macro1()
Dim strImage As StringThe code does what you asked and should only prompt once for the image.
See https://www.gmayor.com/installing_macro.htm