VBA根据Excel内容快速创建PPT

示例需求:根据Excel中选中的单元格内容(3列)如下图所示,在已打卡的PowerPoint文件中创建页面。

新增PPT Slide页面使用第二个模板页面,其中包含两个文本占位符,和一个图片占位符。将Excel选中区域中前两列写入文字占位符,第3列图片粘贴至图片占位符。

示例代码如下。

vb 复制代码
Sub Excel2PPT()
    Dim xlDataRow As Range
    Dim pptApp As PowerPoint.Application
    Dim pptPres As PowerPoint.Presentation
    Dim pptSld As PowerPoint.Slide
    Dim objDic As Object
    Dim xlShp As Shape, i As Integer
    Dim sCellAddress As String
    Set pptApp = GetObject(, "PowerPoint.Application")
    Set pptPres = pptApp.ActivePresentation
    If TypeName(Selection) = "Range" Then
        Set objDic = CreateObject("scripting.dictionary")
        For i = 1 To ActiveSheet.Shapes.Count
            Set xlShp = ActiveSheet.Shapes(i)
            If Not Application.Intersect(xlShp.TopLeftCell, Selection) Is Nothing Then
                Set objDic(xlShp.TopLeftCell.Address) = xlShp
            End If
        Next
        For Each xlDataRow In Selection.Rows
            Set pptSld = pptPres.Slides.AddSlide(pptPres.Slides.Count + 1, pptPres.SlideMaster.CustomLayouts(2))
            pptSld.Select
            With pptSld.Shapes
                .Placeholders(1).TextFrame.TextRange.Text = xlDataRow.Cells(1, 1)
                .Placeholders(2).TextFrame.TextRange.Text = xlDataRow.Cells(1, 2)
                sCellAddress = xlDataRow.Cells(1, 3).Address
                If objDic.exists(sCellAddress) Then
                    objDic(sCellAddress).Copy
                    .Placeholders(3).Select
                    .PasteSpecial DataType:=ppPasteMetafilePicture
                End If
            End With
        Next xlDataRow
    End If
End Sub

【代码解析】

第9行代码获取PowerPoint应用程序。

第10行代码获取PowerPoint应用程序中活动Presentation对象。

第11行代码判断Excel中Selection是否为Range对象,如果选中了其他对象(例如Shape对象),后续代码会产生运行时错误。

第12行代码创建字典对象。

第13~18行代码循环遍历活动工作表中的Shape对象,将选中区域中的Shape对象保存在字典对象中。

第14行代码获取Shape对象。

第15行代码判断Shape对象的锚点单元格(即左上角单元格)是否在选中区域中。

如果满足条件,第16行代码将Shape对象保存在字典对象中,其中锚点单元格的引用地址作为字典的键(Key)。

第19~32行代码循环遍历选中区域的数据行。

第20行代码根据第2个模板页面创建一个新的Slide页面。

第21行代码选中新增的页面。

第23行代码将选中区域中第一列内容写入第一个占位符(Placeholder)中。

第24行代码将选中区域中第2列内容写入第2个占位符(Placeholder)中。

第25行代码获取第3列的单元格引用地址。

第26行代码判断第3列的单元格引用地址是否存在于字典的键中,如果不存在,说明该单元格中没有Shape对象。

如果存在,第24行代码拷贝该单元格中的Shape对象。

第28行代码选中图片占位符。

第29行代码粘贴图片。

运行代码效果如下图所示。

微软在线文档:

Shapes.PasteSpecial method (PowerPoint)

相关推荐
Hello123网站12 小时前
麦当秀|MINDSHOW:在线AI PPT设计工具
人工智能·powerpoint·ai工具
Dxy12393102162 天前
Python如何合并两个Excel文件
爬虫·python·excel
Access开发易登软件3 天前
Access开发右下角浮窗提醒
microsoft·vba·access·access开发
wtsolutions3 天前
Batch Conversion Online JSON Files (from URL) to Excel by WTSolutions
json·excel·batch
码尚云标签3 天前
导入Excel打印
excel·excel导入·标签打印软件·打印知识·excel导入打印教程
sjzmj68134 天前
PPT漏斗图,让数据更美观!
信息可视化·powerpoint·数据可视化·图表在线生成
lilv664 天前
python中用xlrd、xlwt读取和写入Excel中的日期值
开发语言·python·excel
大虫小呓4 天前
14天搞定Excel公式:告别加班,效率翻倍!
excel·excel 公式
WordinPPT_20254 天前
国家科学技术奖答辩PPT案例_科技进步奖ppt制作_技术发明奖ppt设计美化_自然科学奖ppt模板 | WordinPPT
科技·powerpoint·ppt
瓶子xf5 天前
EXCEL-业绩、目标、达成、同比、环比一图呈现
excel