ppt和excel、word一样都可以用vba操作。
正和excel中有Excel→Workbook→Worksheet→Range这样的父子关系对象一样。
ppt也有PowerPoint→Presentation→Slide这样的父子关系对象。
其中PowerPoint表示ppt应用程序,Presentation对象表示所有打开的ppt演示文稿、Slide对象表示演示文稿中的幻灯片。
所有的幻灯片组成了Slides集合对象。
所有的演示文稿组成了Presentations集合对象。
当需要在演示文稿中新增幻灯片时,可以使用Slides集合对象的AddSlide方法。
它的语法如下:
AddSlide( Index, pCustomLayout )
其中index参数为要放置的幻灯片的索引号,pCustomLayout参数为要插入的幻灯片的版式对象。
以下代码将用vba插入一个新的幻灯片,新的幻灯片与第一个幻灯片有一样的版式:
Sub QQ1722187970()
Dim oPPT As Presentation
Dim oSlide As Slide
Dim oCL As CustomLayout
Set oPPT = PowerPoint.ActivePresentation
With oPPT
Set oCL = .Slides(1).CustomLayout
Set oSlide = .Slides.AddSlide(2, oCL)
End With
End Sub
除了可以使用Slides集合对象的AddSlide方法添加幻灯片,还可以使用可以使用Slides集合对象的Add方法添加幻灯片。
它的语法如下:
Function Add(Index As Long, Layout As PpSlideLayout) As Slide
其中index参数为要放置的幻灯片的索引号, Layout参数为要插入的幻灯片的版式常量,它与AddSlide方法不同之处在于 Layout参数是一个常量,不是版式对象。
比如可以使用如下的vba代码插入一个空白的幻灯片:
Sub QQ1722187970()
Dim oPPT As Presentation
Dim oSlide As Slide
Dim oCL As CustomLayout
Set oPPT = PowerPoint.ActivePresentation
With oPPT
Set oSlide = .Slides.Add(1, ppLayoutBlank)
End With
End Sub
以上介绍的都是在ppt 的vba环境中使用vba代码操作ppt,很多时候我们需要的是在excel、word或者其它软件中操作ppt,这时候可以使用如下的通用代码:
Sub QQ1722187970()
Const ppLayoutBlank = 12
Const msoTrue = -1
Const msoFalse = 0
Dim oPPT
' Dim oPPT As PowerPoint.Application
'创建ppt对象
Set oPPT = VBA.CreateObject("PowerPoint.Application")
With oPPT
'使得ppt可见
.Visible = msoTrue
Dim oPresentation
' Dim oPresentation As PowerPoint.Presentation
'获取ppt演示文稿对象
If .Presentations.Count > 0 Then
Set oPresentation = .Presentations(1)
Else
Set oPresentation = .Presentations.Add
End If
With oPresentation
'获取幻灯片对象
Dim oSlide
' Dim oSlide As Slide
If .Slides.Count > 0 Then
Set oSlide = .Slides(1)
Else
Set oSlide = .Slides.Add(1, ppLayoutBlank)
End If
With oSlide
'其它操作代码************
'***********************
End With
End With
End With
End Sub


发表评论