使用VBA删除Powerpoint上的幻灯片,具体取决于Excel单元格

时间:2017-11-09 15:00:26

标签: excel vba excel-vba if-statement powerpoint-vba

我在Excel中有一个删除Powerpoint幻灯片的VBA模块。代码如下:

    Function MyRange(ByVal StartIndex As Long, ByVal StopIndex As Long) As Variant
        Dim A() As Long
        Dim I As Long
        ReDim A(StartIndex To StopIndex)
        For I = StartIndex To StopIndex: A(I) = I: Next
        MyRange = A End Function

Sub RemoveUnwantedSlides()
            ActivePresentation.Slides.Range(MyRange(94, 101)).Delete
            ActivePresentation.Slides.Range(MyRange(85, 92)).Delete
            ActivePresentation.Slides.Range(MyRange(76, 83)).Delete
End Sub

但是,我想要删除幻灯片编号的代码,具体取决于Excel中特定单元格的当前值。假设“1”在单元格A1中,则只应删除幻灯片94-101。如果“2”在单元格A1中,则只应删除幻灯片85-92。如果“3”在单元格A1中,则只应删除幻灯片76-83。

如何在IF语句中插入当前宏? 谢谢

我已经适应了以下情况,但它不起作用:

Sub RemoveUnwantedSlides()
Dim A() As Long
        Dim I As Long
        ReDim A(StartIndex To StopIndex)
        For I = StartIndex To StopIndex: A(I) = I: Next
        MyRange = A

'The file name and path of the file to update
sourceFileName = "C:\Users\Children.pptm"
Set pptApp = New PowerPoint.Application
Set pptPresentation = pptApp.Presentations.Open(sourceFileName)

pptApp.Activate

Dim ppSlidesArr As Variant

Select Case Range("A1").Value
    Case 1
        ppSlidesArr = MyRange(64, 65)

    Case 2
        ppSlidesArr = MyRange(85, 92)

    Case 3
        ppSlidesArr = MyRange(76, 83)

End Select

ActivePresentation.Slides.Range(ppSlidesArr).Delete

End Sub

它给了我一个“运行时错误429:'ActiveX组件无法创建对象' 另外,如果我想删除特定幻灯片而不是范围,我将如何进行?谢谢

1 个答案:

答案 0 :(得分:0)

尝试以下代码,您可以使用Select Case使代码更具可调性,以适应未来的情况:

Sub RemoveUnwantedSlides()

Dim ppSlidesArr As Variant

Select Case Range("A1").Value
    Case 1
        ppSlidesArr = MyRange(94, 101)

    Case 2
        ppSlidesArr = MyRange(85, 92)

    Case 3
        ppSlidesArr = MyRange(76, 83)

End Select

ActivePresentation.Slides.Range(ppSlidesArr).Delete

End Sub