【问题标题】:Delete existing chart in Power Point slide and replace by new chart using VBA删除 Power Point 幻灯片中的现有图表并使用 VBA 替换为新图表
【发布时间】:2018-08-01 13:51:19
【问题描述】:

我正在编写 VBA 代码以将粘贴图表从 excel 复制到 PowerPoint。我的代码将首先从 PowerPoint 幻灯片中删除现有图表,然后再从 Excel 中复制粘贴图表。

不幸的是,某些图表在 PowerPoint 中被命名为“Content Placeholder xx”,因为演示文稿中的现有图表不会被删除。由于内容占位符可以是表格/现成的形状/图表,如何测试内容占位符是图表还是其他形状?

任何指导将不胜感激

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

【问题讨论】:

  • 您知道如何将图表从 Excel 复制/粘贴到 Powerpoint 吗?

标签: vba excel powerpoint


【解决方案1】:

您可以使用 Shape 对象的 HasChart 属性来测试一个形状是否包含图表...

If ActiveSlide.Shapes(i).HasChart Then

如果你还想测试图表的名称,在测试完形状是否有图表...

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

【讨论】:

  • 实际上,只有当形状有图表并且您想删除特定图表时,您才会测试名称。
  • ++ 是的,这是一种方式 :)
【解决方案2】:

使用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

【讨论】:

  • 谢谢希德。我使用了哈希图属性,它工作得很好。我也喜欢你设置图表变量并且什么都不检查的技巧。我会保存它以供将来参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
相关资源
最近更新 更多