简体   繁体   English

VBA:将excel范围粘贴到powerpoint占位符,而不使用.Select

[英]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. 我想在自定义布局中将命名的excel范围粘贴到powerpoint中的内容占位符。 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. 我在这个网站的其他地方看过, 例如这里说要避免使用.Select方法。 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. 编辑,关于Shai的建议。 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 . 首先,它创建所有必需的PowerPoint对象,包括设置Presentation和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). 然后,它循环遍历PPSlide所有Shapes ,当它找到带有Name = "Picture"Shape ,它会检索该工作表中形状的索引,因此它可以将Range对象直接粘贴到此Shape(作为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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