如何用vba给ppt幻灯片插入本地电脑上的图片?

要用vba给ppt幻灯片插入本地电脑上的图片,可以使用Shapes对象的AddPicture或者AddPicture2方法。

其中Shapes对象的AddPicture方法语法如下:

Function AddPicture(FileName As String, LinkToFile As MsoTriState, SaveWithDocument As MsoTriState, Left As Single, Top As Single, [Width As Single = -1], [Height As Single = -1]) As Shape

其中FileName参数为要插入的图片的完整路径,LinkToFile参数和SaveWithDocument参数分别表示是否链接插入的图片以及是否将图片随着ppt文档一起保存。

其中当LinkToFile参数为msoFalse,SaveWithDocument参数必须为msoTrue,这点是特别要注意的。

另外的几个参数分别表示插入的图片位于幻灯片的左上角的位置和图片的长宽大小。

而Shapes对象的AddPicture2方法语法如下:

Function AddPicture2(FileName As String, LinkToFile As MsoTriState, SaveWithDocument As MsoTriState, Left As Single, Top As Single, [Width As Single = -1], [Height As Single = -1], [compress As MsoPictureCompress = msoPictureCompressDocDefault]) As Shape

它只比AddPicture方法多了一个参数compress,用于指定插入的图片是否需要压缩。

根据以上的这些知识,可以使用如下的vba代码在ppt的第一个幻灯片中插入一个本地电脑上的图片:

Sub QQ1722187970()
    Const ppLayoutBlank = 12
    Const msoTrue = -1
    Const msoFalse = 0
'    Dim oPPT
    Dim oPPT As PowerPoint.Application
    Set oPPT = PowerPoint.Application
    '创建ppt对象
'    Set oPPT = VBA.CreateObject("PowerPoint.Application")
    With oPPT
'        '使得ppt可见
'        .Visible = msoTrue
          Dim oPresentation As PowerPoint.Presentation
        '获取ppt演示文稿对象
        If .Presentations.Count > 0 Then
            Set oPresentation = .Presentations(1)
        Else
            Set oPresentation = oPPT.Presentations.Add
        End If
        With oPresentation
            '获取幻灯片对象
            Dim oSlide As Slide
            If .Slides.Count > 0 Then
                '等于第一个幻灯片
                Set oSlide = .Slides(1)
            Else
                Set oSlide = .Slides.Add(1, ppLayoutBlank)
            End If
            With oSlide
                Dim oSP As Shape
                '插入一个图片
                Set oSP = .Shapes.AddPicture(oPresentation.Path & "\1.png", msoFalse, msoTrue, 0, 0)
                '其它操作代码************
                '***********************
            End With
        End With
    End With
End Sub
       

发表评论