简体   繁体   English

删除Power Point幻灯片中的现有图表,并使用VBA替换为新图表

[英]Delete existing chart in Power Point slide and replace by new chart using VBA

I am writing VBA code to copy paste chart from excel to PowerPoint. 我正在编写VBA代码以将粘贴图表从excel复制到PowerPoint。 My code would first delete the existing chart from the PowerPoint slide before copy pasting the chart from excel. 我的代码将首先从PowerPoint幻灯片中删除现有图表,然后从excel复制粘贴图表。

Unfortunately some of charts are named as “ Content Placeholder xx ” in PowerPoint due to which existing chart in presentation wouldn't get deleted. 不幸的是,一些图表在PowerPoint中被命名为“ 内容占位符xx ”,因为现有的图表不会被删除。 Since content placeholder can be table/ ready-made shape /chart, how can I test if content place holder is chart or some other shape? 由于内容占位符可以是表格/现成的形状/图表,如何测试内容占位符是图表还是其他形状?

Any guidance will be appreciated 任何指导将不胜感激

Sub Powerpoint_Slide_MoveChart()

    '// General declaration
    Dim ppt             As PowerPoint.Application
    Dim ActiveSlide     As PowerPoint.Slide
    Dim Cht             As ChartObject
    Dim i               As Integer

    '// Set powerpoint application
    Set ppt = GetObject(, "PowerPoint.Application")

    '// Check if more then single powerpoint open
    If ppt.Presentations.Count > 1 Then
        MsgBox "Please close all other powerpoints except the one you would like to puiblish."
        Exit Sub
    End If

    '// Set active slide as slide 9
    Set ActiveSlide = ppt.ActivePresentation.Slides(9)
    ppt.ActiveWindow.View.GotoSlide (9)
    Set Cht = ActiveSheet.ChartObjects("ChartSlide9")

    '// Delete existing chart
    For i = 1 To ActiveSlide.Shapes.Count
        If Left(UCase(ActiveSlide.Shapes(i).Name), 5) = "CHART" Then
            ActiveSlide.Shapes(i).Delete
            Exit For
        End If
    Next i
 End Sub

You can test whether a shape contains a chart by using the HasChart property of the Shape object... 您可以使用Shape对象的HasChart属性测试形状是否包含图表...

If ActiveSlide.Shapes(i).HasChart Then

If you also wanted to test for the name of the chart, after testing whether the shape had a chart... 如果您还想测试图表的名称,请在测试图形是否有图表之后...

If ActiveSlide.Shapes(i).Chart.Name = "Chart Name" Then

Use the Shapes.Chart Property 使用Shapes.Chart属性

Sub Sample()
    Dim chrt As Chart

    With ActivePresentation
        For i = 1 To .Slides(1).Shapes.Count
            On Error Resume Next
            Set chrt = .Slides(1).Shapes(i).Chart
            On Error GoTo 0

            If Not chrt Is Nothing Then
                MsgBox "Guess what? " & .Slides(1).Shapes(i).Name & " is a chart"
                Set chrt = Nothing
            Else
                MsgBox .Slides(1).Shapes(i).Name & " is not a chart"
            End If
        Next i
    End With
End Sub

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

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