简体   繁体   中英

VBA: Paste excel range to powerpoint placeholder without using .Select

I want to paste a named excel range to a content placeholder in powerpoint in a custom layout. I'm currently using code like this

ranger.Copy
currentPPT.ActiveWindow.View.GotoSlide ppt.slides.Count
activeSlide.shapes("Picture").Select msoTrue
ppt.Windows(1).View.PasteSpecial (ppPasteEnhancedMetafile)

It usually works but sometimes fails inexplicably. I have seen elsewhere on this site, here for example , saying to avoid using .Select method. Instead use something like

Dim oSh As Shape
Set oSh = ActivePresentation.Slides(9).Shapes.PasteSpecial(ppPasteEnhancedMetafile)(1)

However, I can't figure out how to use the second method to copy straight to a content placeholder. Is that possible?

Edit, regarding Shai's suggestion. Current code is

For ii = activeSlide.shapes.Count To 1 Step -1
If activeSlide.shapes.Item(ii).Name = "Picture" Then
    shapeInd = ii
    Exit For
End If
Next ii

Set oSh = activeSlide.shapes.PasteSpecial(2, msoFalse)(shapeInd)

The "Picture" shape is a "Content" Placeholder. The other two shapes are text boxes.

The code below will do as you mentioned in your post.

First it creates all the necessary PowerPoint objects, including setting the Presentation and PPSlide .

Afterwards, it loops through all Shapes in PPSlide , and when it finds the Shape with Name = "Picture" it retrieves the index of the shape in that sheet, so it can Paste the Range object directly to this Shape (as Placeholder).

Code

Option Explicit

Sub ExporttoPPT()

Dim ranger          As Range
Dim PPApp           As PowerPoint.Application
Dim PPPres          As Presentation
Dim PPSlide         As Slide
Dim oSh             As Object

Set PPApp = New PowerPoint.Application
Set PPPres = PPApp.Presentations("PPT_TEST") ' <-- change to your open Presentation
Set PPSlide = PPPres.Slides(9)

Set ranger = Worksheets("Sheet1").Range("A1:C5")    
ranger.Copy

Dim i As Long, ShapeInd As Long

' loop through all shapes in Slide, check for Shape Name = "Picture"
For i = PPSlide.Shapes.Count To 1 Step -1
    If PPSlide.Shapes.Item(i).Name = "Picture" Then
        ShapeInd = i '<-- retrieve the index of the searched shape
        Exit For
    End If
Next i

Set oSh = PPSlide.Shapes.PasteSpecial(2, msoFalse)(ShapeInd) ' ppPasteEnhancedMetafile = 2

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM