ahinkle
ahinkle

Reputation: 2261

PowerPoint VBA: Copy and paste image, align to center, and stretch to fit page

I'm trying to create a command to automatically export a PDF in PowerPoint.

I have a command to paste a photo that is working. However, it just pastes to the top left of the screen.

I have been looking on the web for a script to align to the center of the slide and stretch to fit the slideshow page. I tried to record it but it seems as if PowerPoint does not have a record function.

Here is my Copy + Paste script that works below.

Sub PastePhoto()
Dim Sld As Slide
'Ensure focus is on slide
Application.ActiveWindow.Panes(2).Activate

Set Sld = Application.ActiveWindow.View.Slide

On Error GoTo NoCopy
    Sld.Shapes.PasteSpecial (ppPasteEnhancedMetafile)
On Error GoTo 0

Exit Sub

NoCopy:
MsgBox "There was nothing copied to paste!"

Upvotes: 2

Views: 8477

Answers (2)

ahinkle
ahinkle

Reputation: 2261

After some tweaking I've figured it out :)

Sub PastePhoto()

Const ppLayoutBlank = 12

Dim objWorkSheet As Worksheet
Dim objRange As Range
Set objWorkSheet = ThisWorkbook.ActiveSheet

Range("A1:H18").Select
Range("H18").Activate
Selection.Copy

Dim objPPT As PowerPoint.Application
Dim objPresentation As Presentation
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True

Set objPresentation = objPPT.Presentations.Add
Set objSlide = objPresentation.Slides.Add(1, 1)

objPresentation.Slides(1).Layout = ppLayoutBlank

' paste as the meta file
objPPT.Windows(1).View.PasteSpecial ppPasteMetafilePicture, msoTrue, , ,         "testlabel"
End Sub

Upvotes: 0

Bond
Bond

Reputation: 16311

This should be all that's needed to insert a picture into your slide and stretch it to fit the slide's width:

' Get the first slide...
Dim sl As Slide
Set sl = ActivePresentation.Slides(1)

' Insert a picture at (0, 0)...
Dim sh As Shape
Set sh = sl.Shapes.AddPicture("c:\path\to\my.jpg", msoFalse, msoTrue, 0, 0)

' Set the picture's width to that of a slide...
sh.Width = ActivePresentation.PageSetup.SlideWidth

And if you want to center it vertically:

sh.Top = (ActivePresentation.PageSetup.SlideHeight - sh.Height) / 2

Upvotes: 2

Related Questions