Adjust image properties with AddPicture Method word vba - vba

I need to edit the properties of an image inserted by AddPicture method.
1) I need to adjust the height to 0.5" and the width is variable (lock the aspect ratio).
2) Wrap text = "In Front of Text"
Is this possile with this method? If so how do I add those properties? If not, what other method should I use and how?
Sub replaceWithImage()
Dim imageFullPath As String
Dim FindText As String
imageFullPath = "C:\Logo.jpg"
FindText = "PlaceHolder"
'Application.ScreenUpdating = False
With Selection
.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.text = FindText
' Loop until Word can no longer
' find the search string, inserting the specified image at each location
Do While .Execute
Selection.MoveRight
Selection.InlineShapes.AddPicture FileName:=imageFullPath, LinkToFile:=False, SaveWithDocument:=True
Loop
End With
End With
End Sub

I would do what you need in the following steps:
instead of this line:
Selection.InlineShapes.AddPicture FileName:=imageFullPath, _
LinkToFile:=False, SaveWithDocument:=True
I would do the same but using Object Variable:
'a) create new shape as object variable
Dim SHP 'As InlineShape/As Shape
Set SHP = Selection.InlineShapes.AddPicture(FileName:=imageFullPath, _
LinkToFile:=False, _
SaveWithDocument:=True)
'b) changes made according to SHP varialbe:
With SHP
'this will convert to 'in front of text'
.ConvertToShape
'this will keep ratio
.LockAspectRatio = msoTrue
'this will adjust width to 0.5 inch
.Width = InchesToPoints(0.5)
End With

Related

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.

Problem inserting Image at a specific position

I have been using the word VBA Shapes.AddPicture method (as in Add image to Word document at specified position) to insert a Png in a specific position of a document (near text previously found with Selection.Find.Execute...) and all has been working without problems for years, but now, without any change (nor in doc nor in code) the image has begun to go to top left corner and I couldn't find a reason...
Does someone know if something has change about that in last updates or what is happening?
I'm using properly updated 365 version and my code is:
Dim mySignatureShape As shape
Dim myImagePath as string
Selection.Find.Execute FindText:=" Text to find Here "
Selection.Collapse
myLeft = "-25"
myTop = "-49"
myImagePath = "Full Image Path Here"
Set mySignatureShape = ActiveDocument.Shapes.AddPicture(Filename:=myImagePath, LinkToFile:=False, _
SaveWithDocument:=True,
Anchor:=Selection.Range, _
Width:="275", Height:="150", _
Left:=myLeft, Top:=myTop)
Your code is missing anything to tell Word where to position the image in relation to the found text. As such, it could never have positioned the image 'near' that text unless the text was itself near the top of the page. Try:
Application.ScreenUpdating = False
Dim mySignatureShape As Shape
Dim myImagePath As String
Dim myLeft As Long, myTop As Long
myImagePath = "Full Image Path"
With Selection
.Find.Execute FindText:="Text to find"
.Collapse wdCollapseStart
myLeft = -25 + .Information(wdHorizontalPositionRelativeToPage)
myTop = -49 + .Information(wdVerticalPositionRelativeToPage)
Set mySignatureShape = ActiveDocument.Shapes.AddPicture(FileName:=myImagePath, LinkToFile:=False, _
SaveWithDocument:=True, Anchor:=.Range, Width:=275, Height:=150, Left:=myLeft, Top:=myTop)
End With
Application.ScreenUpdating = True

Word footer image alignment in VBA

I try to put a signature in the footer of a word document, but I can't align it at the bottom right of the footer.
Also, in my footer there is a line of text (i.e. my Company Inc) and the signature must be exactly over the text, as in the screenshot:
Any help, please?
My code, which works except for the positioning:
Sub Macro1()
Dim SHP as String
FIRMADOC = "C:\Users\user\Pictures\1.png"
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
Set SHP = Selection.InlineShapes.AddPicture(FileName:=FIRMADOC, LinkToFile:=False, SaveWithDocument:=True)
With SHP
'AJUSTA A "ENFRENTE DEL TEXTO"
.ConvertToShape
' MANTIENE EL RATIO
.LockAspectRatio = msoTrue
'AJUSTA A ANCHO 1 inch
.Width = InchesToPoints(1)
' .Alignment = ' need this code for bottom-right, PLEASE
End With
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End sub
Because Shape objects "float" on the page, they can be easily positioned. They can also be easily (and accidentally) repositioned. Shape objects can also be tricky to hanlde using code. So a useful rule-of-thumb I use is: if an InlineShape works, use it rather than a Shape.
Three possibilities are out-lined, below; two for InlineShapes and one for a Shape.
An InlineShape can be positioned right-aligned to the page using two different methods (depending on whether it's alone in the paragraph).
Right-align the paragraph which contains the InlineShape. This is appropriate when the paragraph has no other content. Extracting just the code from the question for handling this:
Dim SHP as InlineShape
Set SHP = Selection.InlineShapes.AddPicture(FileName:=FIRMADOC, _
LinkToFile:=False, SaveWithDocument:=True)
SHP.Range.ParagraphFormat.Alignment = wdAlignParagraphRight
If the paragraph has other content to the left, then a right-aligned TAB stop with a TAB character preceding the InlineShape will work. A Footer by default has two TAB stops: one center-aligned, the second right-aligned.
For this, I'm going to change the entire code in the question in order to optimize working in a Footer. (The same approach applies to a Header BTW). The macro recorder produces code that emulates user actions, so it actually opens up the footer (or header) using things like ActiveWindow and Selection. These are somewhat difficult to control precisely; working with the actual Word objects is more reliable.
Think of a Range object like an invisible selection. The entire Footer area is assigned to a range (rng). Since the Footer already has content (the "Company Inc" text), it's necessary to "collapse" the Range. (Think of it like pressing left-arrow so that new content does not replace a selection.)
Then two TAB characters are added to it (rng.Text = vbTab & vbTab) and the signature is added.
Sub Macro1()
Dim FIRMADOC as String
Dim SHP as InlineShape
Dim rng as Word.Range
FIRMADOC = "C:\Users\user\Pictures\1.png"
Set rng = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
rng.Collapse wdCollapseStart
rng.Text = vbTab & vbTab 'position at second, right-aligned tab in the footer)
Set SHP = rng.InlineShapes.AddPicture(FileName:=FIRMADOC, LinkToFile:=False, SaveWithDocument:=True, Range:=rng)
With SHP
' MANTIENE EL RATIO
.LockAspectRatio = msoTrue
'AJUSTA A ANCHO 1 inch
.Width = InchesToPoints(1)
End With
End sub
If it's necessary to use a Shape object, then a combination of the Left and RelativeHorizontalPosition properties is required. Members of the wdShapePosition and WdRelativeHorizontalPosition enumerations specify these special settings.
Note that it also might be necessary to include the Top property to get the correct vertical position of the Shape to the "Company, Inc" text.
Sub Macro1()
Dim FIRMADOC as String
Dim SHP as InlineShape
Dim rng as Word.Range
FIRMADOC = "C:\Users\user\Pictures\1.png"
Set rng = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
rng.Collapse wdCollapseStart
Set SHP = rng.InlineShapes.AddPicture(FileName:=FIRMADOC, LinkToFile:=False, SaveWithDocument:=True, Range:=rng)
Set SHP = SHP.ConvertToShape
With SHP
' MANTIENE EL RATIO
.LockAspectRatio = msoTrue
'AJUSTA A ANCHO 1 inch
.Width = InchesToPoints(1)
.Left = wdShapeRight '-999996
.RelativeHorizontalPosition = wdRelativeHorizontalPositionMargin '0
End With
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 to add a custom Text placeholder in one of the master slides in MS Power Point presentation and access it using VBA Script for each slide?

I have created a custom placeholder namely "CustomHeader" of Text Box Type on one of the slides in my Power Point presentation. How can I iterate through all slides inserting the Presentation Title into this placeholder.
I have the following code, which enters the Page No in a custom format in the footer. It also inserts the Section to the footer of the slides. I would like to enter something in the CustomHeader placeholder to every matching slide.
Sub SecFootNew()
Dim oshp As Shape
Dim b_found As Boolean
If ActivePresentation.SectionProperties.Count > 0 Then
Dim osld As Variant
For iSlide = 1 To ActivePresentation.Slides.Count
' Need Help with These
With ActivePresentation.Slides(2).Shapes.Placeholders(CustomHeader).TextFrame.TextRange
.Text = "Happy Honika"
End With
' The Following portion of the code is working Perfectly
If iSlide <> 1 Then
Set osld = ActivePresentation.Slides(iSlide)
' Configure Display of Page Number
With osld.HeadersFooters.DateAndTime
.Visible = False ' True For making the Date Visible
' .UseFormat = True
' .Format = ppDateTimedMMMyy
End With
' Configure Footer
osld.HeadersFooters.Footer.Visible = True
osld.HeadersFooters.SlideNumber.Visible = True
For Each oshp In osld.Shapes
If oshp.Type = msoPlaceholder Then
If oshp.PlaceholderFormat.Type = ppPlaceholderFooter Then
With oshp.TextFrame.TextRange
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Color = RGB(255, 255, 255)
.Text = ActivePresentation.SectionProperties.Name(osld.sectionIndex)
End With
End If
If oshp.PlaceholderFormat.Type = ppPlaceholderSlideNumber Then
With oshp.TextFrame.TextRange
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Color = RGB(255, 255, 255)
.Text = "Slide " & CStr(osld.SlideIndex) & " of " & CStr(ActivePresentation.Slides.Count)
End With
End If
End If
Next oshp
End If
Next iSlide
End If
End Sub
As you can't add placeholders to slides I assume you mean that you have added a Text Placeholder to one of the Custom Layouts in the Slide Master and you have renamed that placeholder "CustomHeader".
When a slide based on that layout is added to the presentation your placeholder will no longer be called "CustomHeader". Instead it will be called something like "Text Placeholder 3". So your first task is to find the name PowerPoint gives your placeholder when it is inserted.
Then you can simply include an extra condition within your loop:
if oshp.Name = "Text Placeholder #" then _
oshp.TextFrame.TextRange.Text = "Happy Honika"