Insert an image to a bookmark and resize - vba

I am trying to insert and resize an image in word 2019 using vba. I have lot of images to insert and using vba will save a lot of time.
The issue is that I can select the image, but the height does not change. I am sure it is something pretty basic that I am doing wrong. The code, which I found online and I have adjusted a little, is below and any advice would be great. Thank you.
Sub insertimage()
On Error Resume Next
' InsertPic Macro
Dim FD As FileDialog
Dim strPictureFile As String
Dim wrdDoc As Word.Document
Dim ishp As Word.InlineShapes
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.Title = "Select the Picture that you wish to insert."
.Filters.Clear
.Filters.Add "Pictures", "*.jpg; *.bmp; *.gif"
.AllowMultiSelect = False
If .Show = -1 Then
strPictureFile = .SelectedItems(1)
Else
MsgBox "You did not select a Picture."
Exit Sub
End If
End With
Set wrdDoc = ActiveDocument
With wrdDoc
If .Bookmarks.Exists("BasketIso1") Then
.InlineShapes.AddPicture FileName:=strPictureFile, LinkToFile:=False, SaveWithDocument:=True, Range:=.Bookmarks("BasketIso1").Range
.InlineShapes(1).LockAspectRatio = True
.InlineShapes(1).Height = InchesToPoints(1.78)
End If
End With
End Sub
`

You seem to see the picture being inserted, which suggests that the code up to and including .AddPicture works OK.
But then you are referencing the first picture in the document via .InlineShapes(1) (i.e. that does not reference the first picture in the bookmarks range). If it isn't actually the first picture, another picture will be resized (and you may not notice if it is already set to that size.
So you could redefine the type of ishp, which you don't seem to use at present, using
Dim ishp As Word.InlineShape
then use
Set ishp = .InlineShapes.AddPicture(FileName:=strPictureFile, LinkToFile:=False, SaveWithDocument:=True, Range:=.Bookmarks("BasketIso1").Range)
ishp.LockAspectRatio = True
ishp.Height = InchesToPoints(1.78)
Set ishp = Nothing
or a variation on that, e.g.
Set ishp = .InlineShapes.AddPicture(FileName:=strPictureFile, LinkToFile:=False, SaveWithDocument:=True, Range:=.Bookmarks("BasketIso1").Range)
With ishp
.LockAspectRatio = True
.Height = InchesToPoints(1.78)
End With
Set ishp = Nothing
or the
With .InlineShapes.AddPicture(FileName:=strPictureFile, LinkToFile:=False, SaveWithDocument:=True, Range:=.Bookmarks("BasketIso1").Range)
.LockAspectRatio = True
.Height = InchesToPoints(1.78)
End With
NB, probably not a problem in this case but using a generic
On Error Resume Next
when debugging can make it harder to see the cause of an error.

Related

When looping through all images, how to indicate the one which is current dealing with?

I would like to use VBA to change the width of the images on-by-one in the doc. I need to manually judge wether the current image should be changed or not with a yes-or-no message box when looping through.
The current code is listed below, it works, but the problem is that WORD does not indicate which image is the current one.
Thanks!
Sub change_images()
Dim iShp As InlineShape
For Each iShp In ActiveDocument.InlineShapes
With iShp
If .Type = wdInlineShapePicture Then
iShp.Select
CarryOn = MsgBox("Change current image?", vbYesNo, "")
If CarryOn = vbYes Then
.LockAspectRatio = msoTrue
.Width = 28.345 * 12
End If
End If
End With
Next
End Sub
I tried to add a .Select before the MsgBox line, but the usually selection mark can not be viewed when the code is running.
iShp.Select
Application.ScreenRefresh
You can be solved by using ScreenRefresh method.

Keep Picture Ratio in Word File

I add a picture via VBA in the Left Header Cell of a Word document - works fine with the following code. Now I want to keep the ratio of the Picture but want to change the size and I don't know how to do it:
Sub AutoOpen()
Dim dd1 As Document: Set dd1 = ActiveDocument
Dim rng1 As Range, seC As Section, an(2) As Long
Dim rngO As Range, rngAN As Range
Dim strToPict As String
For Each rngO In dd1.StoryRanges
ActiveDocument.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
If rngO.StoryType = wdEvenPagesHeaderStory Then
Set rng1 = rngO.Duplicate
For Each seC In rng1.Sections
an(0) = seC.Headers(1).Range.InlineShapes(1).Height
an(1) = seC.Headers(1).Range.InlineShapes(1).Width
Set rngAN = seC.Headers(1).Range.InlineShapes(1).Range.Duplicate
seC.Headers(1).Range.InlineShapes(1).Delete
seC.Headers(1).Range.InlineShapes.AddPicture FileName:=strToPict, _
LinkToFile:=False, SaveWithDocument:=True, Range:=rngAN
With seC.Headers(1).Range.InlineShapes(1)
.Height = 50
.LockAspectRatio = True
End With
Next
Dim i As Long
ActiveDocument.Save
'Footer changing'
For i = 1 To ActiveDocument.Sections.Count
With ActiveDocument.Sections(i)
.Footers(wdHeaderFooterPrimary).Range.Text = ActiveDocument.Name + "Text"
End With
Next
End If
Next
End Sub
EDIT: I post the whole code of the Makro.
«I add a picture via VBA in the Left Header Cell of a Word document». There is no such thing as a 'Left Header Cell' in a Word document. The only headers (and footers) Word has are Primary, First Page and Even Pages.
And, as Timothy said, you "really need to learn to use the tools at you fingertips". Moreover, having found LockAspectRatio, a simple web search - if that was really necessary - would show you how to use it.
In any event, since all it seems you're trying to do is to resize the inlineshape and repeat the primary page header, you could use something along the lines of:
Sub AutoOpen()
Application.ScreenUpdating = False
Dim Rng As Range, iShp As InlineShape, Sctn As Section, StrNm As String
With Dialogs(wdDialogInsertPicture)
.Display
StrNm = .Name
End With
With ActiveDocument
If StrNm <> "" Then
Set Rng = .Sections.First.Headers(wdHeaderFooterPrimary).Range.Tables(1).Cell(1, 1).Range
Set iShp = .InlineShapes.AddPicture(FileName:=StrNm, _
LinkToFile:=False, SaveWithDocument:=True, Range:=Rng)
With iShp
.LockAspectRatio = True
.Height = 50
End With
End If
Set Rng = .Sections.First.Footers(wdHeaderFooterPrimary).Range
.Fields.Add Range:=Rng, Type:=wdFieldEmpty, Text:="FILENAME", PreserveFormatting:=False
Rng.InsertAfter vbTab & "Text"
For Each Sctn In .Sections
Sctn.Headers(wdHeaderFooterPrimary).LinkToPrevious = True
Sctn.Footers(wdHeaderFooterPrimary).LinkToPrevious = True
Next
End With
Application.ScreenUpdating = True
End Sub
You really need to learn to use the tools at you fingertips - IntelliSense, the Object Browser, and online help.
Scrolling through the options that IntelliSense gives you, or looking up InlineShape in the Object Browser, you would find LockAspectRatio. If you weren’t sure whether that was what you needed, pressing F1 would take you to the online help.

Hide Microsoft Word Shape Border While Printing

I need some help regarding the Shapes Layout in Word Format. I have a word template that has some shapes in it, I want the result when the user tries to print the file or save it in PDF, it should not include the shape borders in it.
My Word File: Download Here
Desired File: Download Here
Actual File - While Editing The Document
While Printing CTRL+P (Desired Result)
I have found a script online that removes the shapes completely, I only want to remove the borders and retain the text/images inside the shape.
The script is as follows:
Sub PrintNoImagesOrShapesInDoc()
Dim objDoc As Document
Dim objInLineShape As InlineShape
Dim objShape As Shape
' Initialization
Set objDoc = ActiveDocument
' Find all images and shapes in the active document and then hide them to prevent from being
printed.
With objDoc
For Each objInLineShape In .InlineShapes
objInLineShape.Select
Selection.Font.Hidden = False
Next objInLineShape
Options.PrintDrawingObjects = False
End With
Dialogs(wdDialogFilePrint).Show
With objDoc
For Each objInLineShape In .InlineShapes
objInLineShape.Select
Selection.Font.Hidden = False
Next objInLineShape
End With
End Sub
Any Positive Help will be appreciated
Thanks,
For example, to save as a PDF:
Sub Demo()
Application.ScreenUpdating = False
Dim objUndo As UndoRecord, Shp As Shape
Set objUndo = Application.UndoRecord
With ActiveDocument
objUndo.StartCustomRecord ("RecordName")
For Each Shp In .Shapes
Shp.Line.Visible = False
Next
.SaveAs FileName:=Split(.FullName, ".doc")(0) & ".pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False
objUndo.EndCustomRecord
.Undo
End With
Application.ScreenUpdating = True
End Sub

Insert a picture into an InlineShape

I’m writing a Document in which I have to include many Pictures. In the ongoing process the Pictures get changed many times.
My idea was to include Rectangle Shapes as placeholders and give them a suitable name. I created a Macro that selects the Shape, deletes the old Picture and inserts the new one into the Shape.
Sub InsertImage(Shape As String, Picture As String, Hight As Integer)
Dim shp As Word.Shape
Dim strFile As String
Dim strExt As String
strFile = "C:\Pictures"
strExt = ".png"
ActiveDocument.Shapes.Range(Array(Shape)).Select
Selection.TypeBackspace
Set shp = ActiveDocument.Shapes.AddPicture(Anchor:=Selection.Range, FileName:= _
strFile & "\" & Picture & strExt, LinkToFile:=False, SaveWithDocument:=True)
With shp
.LockAspectRatio = msoTrue
.Height = CentimetersToPoints(Hight)
End With
End Sub
Sub Insert1()
InsertImage "Shape01", "Pic01", 10
End Sub
I want this for floating Shapes as well as for InlineShapes.
When I set my Placeholder Shapes to InlineShapes the TypeBackspace line deletes the InlineShape and the picture does not get inserted into the InlineShape.
Thank you very much for the help. After many struggles, the solution with Tables + Bookmarks works perfekt.
Here is the code:
Sub InsertPic(Pic As String, Cut As Single)
Dim strFile As String
Dim strExt As String
Dim ils As InlineShape
strFile = "C:\Pictures“
strExt = ".png"
Application.ScreenUpdating = False
ActiveDocument.Bookmarks(Pic).Select
Selection.Delete
Set ils = Selection.InlineShapes.AddPicture(FileName:= _
strFile & "/" & Pic & strExt, _
LinkToFile:=False, SaveWithDocument:=True)
With ils
.PictureFormat.CropBottom = CentimetersToPoints(Cut)
.LockAspectRatio = msoTrue
.Height = .Range.Cells(1).Height
If .Width > .Range.Cells(1).Width Then
.Width = .Range.Cells(1).Width
End If
End With
ActiveDocument.Bookmarks.Add (Pic)
Application.ScreenUpdating = True
End Sub
Sub Insert01()
InsertPic "Image01", 20
MsgBox "Done"
End Sub
Some explanation:
For this code, the Bookmark and the Picture need the same Name. I made this to avoid mix-ups.
With the Selection.Delete command, the Bookmark gets also deleted, so I just added a new Bookmark with the same name at the end. I’m sure there are more elegant ways to solve this, but this solution works.
I have had many struggles because i wanted to crop the Picure. But the size gets changed to the size of the table-cell when its inserted and the cutting step comes afterwards. So the Picturs wasn´t filling the complete cell size. Therefore, I added a part to resize the Image to the table-cell Size. As well, im sure there are better ways to overcome this ...
Because of this resizing, the Makro needs a bit of time (at least for my document). So I disabled the Screenupdating.

How can I insert a footer image into a docx Document via Visual Basic? (Mac)

I got a .docx Document created with Apache POI. I opened it and tried to insert header and footer images by executing two macros:
Sub Header_Bild_Einfuegen()
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect
End If
Dim oShape As Shape, oRange As Range
Dim Pfad As String
Pfad = "C:\Users\path\to\headerIcon.jpeg"
Set oRange = ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
Set oShape = ActiveDocument.Shapes.AddPicture(FileName:=Pfad, _
LinkToFile:=False, SaveWithDocument:=True, Anchor:=oRange)
oShape.Height = CentimetersToPoints(4.8)
oShape.Width = CentimetersToPoints(21.55)
oShape.Left = CentimetersToPoints(-2.44)
oShape.Top = CentimetersToPoints(-1.28)
oShape.ZOrder msoSendBehindText
End Sub
Sub Footer_Bild_Einfuegen()
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect
End If
'
Dim oShape As Shape, oRange As Range
Dim Pfad As String
Pfad = "C:\Users\path\to\footerIcon.jpeg"
Set oRange = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
Set oShape = ActiveDocument.Shapes.AddPicture(FileName:=Pfad, _
LinkToFile:=False, SaveWithDocument:=True, Anchor:=oRange)
oShape.Height = CentimetersToPoints(2.4)
oShape.Width = CentimetersToPoints(21.55)
oShape.Left = CentimetersToPoints(-2.44)
oShape.ZOrder msoSendBehindText
End Sub
My problem is:
Both images are inserted into the header of the document, the footer stays empty (but exists, contains text (so does the header)).
I tried to change pretty much everything, but all ended up giving me runtime errors. I even changed the variable names for Footer_Bild_Einfuegen() because I thought they might be merging both macros for any reason (No runtime error, just didn't work. It ended up the same way as it did when the variables names were equal).
It all works fine under Windows, but it fails under Mac.
I have no idea what this could be caused by, maybe it's just the implmentation of VB in the Mac-Office edition (MS Office 2008 for Mac, MS Office 2016 does not work either), I don't know.
If there is no solution for this problem, is there a convenient way to insert images into the footer without having to resize them manually every time?
Thanks in advance, appreciate every answer
I finally found a way:
Sub Finalize()
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect
End If
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Or ActiveWindow.ActivePane.View.Type = wdMasterView Then
ActiveWindow.ActivePane.View.SeekView = wdPageView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
ActiveDocument.PageSetup.FooterDistance = InchesToPoints(1)
Dim oShape As Shape, oRange As Range
Dim Pfad As String
Pfad = "/Path/To/footerIcon.jpeg"
Set oRange = Selection.Range
Set oShape = ActiveDocument.Shapes.AddPicture(fileName:=Pfad, LinkToFile:=False, SaveWithDocument:=True, Anchor:=oRange)
oShape.Height = CentimetersToPoints(2.2)
oShape.Width = CentimetersToPoints(21.55)
oShape.Left = CentimetersToPoints(-2.44)
oShape.Top = CentimetersToPoints(0.28)
oShape.ZOrder msoSendBehindText
'HEADER
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Dim ohShape As Shape, ohRange As Range
Dim hPfad As String
hPfad = "/Path/To/headerIcon.jpeg"
Set ohRange = Selection.Range
Set ohShape = ActiveDocument.Shapes.AddPicture(fileName:=hPfad, LinkToFile:=False, SaveWithDocument:=True, Anchor:=ohRange)
ohShape.Height = CentimetersToPoints(4.6)
ohShape.Width = CentimetersToPoints(21.55)
ohShape.Left = CentimetersToPoints(-2.44)
ohShape.Top = CentimetersToPoints(-1.28)
ohShape.ZOrder msoSendBehindText
ActiveDocument.ActiveWindow.View.Type = wdPrintView
End Sub
This way should also work under Windows.