问与答115:如何使用VBA从Excel中复制图片并将其粘贴到PowerPoint的指定幻灯片?
excelperfect
Q:我在Excel工作表中包含有1张图片,名称是默认的“图片 1”,我怎样编写VBA代码来打开一个已存在的PPT文件,先删除该PPT中所有的图片,然后将“图片 1”复制并粘贴到该PPT的第2张幻灯片中。
A:首先,添加对“MicrosoftPowerPoint XX.0 Object Library”库的引用,如下图1所示。
图1
然后,输入如下代码:
Sub PPT_Autom()
Dim ObjPPT As PowerPoint.Application
Dim oPresentation AsPowerPoint.Presentation
Dim oSlide As PowerPoint.Slide
Dim oShape As PowerPoint.Shape
Dim i As Long
Dim opath As String
opath = 'E:\问与答115\exceltoppt.pptx'
Set ObjPPT = New PowerPoint.Application
ObjPPT.Visible = msoCTrue
Set oPresentation =ObjPPT.Presentations.Open(opath, msoCTrue)
'删除PPT中的所有图片
For Each oSlide In oPresentation.Slides
For i = oSlide.Shapes.Count To 1 Step-1
Set oShape = oSlide.Shapes(i)
If oShape.Type = msoPicture Then oShape.Delete
Next i
Next oSlide
Sheet1.Shapes('图片 1').Copy
ObjPPT.Activate
ObjPPT.ActiveWindow.View.GotoSlide (2)
ObjPPT.ActivePresentation.Slides(2).Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
With ObjPPT.ActiveWindow.Selection.ShapeRange
.LockAspectRatio = False
.Left = 50
.Top = 50
.LockAspectRatio = False
.Height = 300
.Width = 300
End With
Set oSlide = Nothing
Set oPresentation = Nothing
End Sub
小结:
Excel与其他Office应用程序(例如Word、PowerPoint)相交互是常见的应用,因为他们都属于Office家族,因此很方便整合。
注:今天的这个问题来源于mrexcel.com论坛,略有修改,供有兴趣的朋友学习参考。