通过VBA获取PPT演示文稿的活动幻灯片(但从Excel!)

时间:2019-07-19 18:02:23

标签: excel vba powerpoint

我想执行以下代码,但是使其可以在Excel中运行!

ActiveWindow.Selection.SlideRange.SlideIndex

是否有机会在不将宏放入PowerPoint文件的情况下获得选定的幻灯片索引?

2 个答案:

答案 0 :(得分:1)

请尝试通过以下方式使用PowerPoint可能正在运行的实例:

Private Sub ControlPowerPointFromExcelEarlyBinding()
    Dim ppApp As PowerPoint.Application
    Dim ppPres As PowerPoint.Presentation
    Dim ppSlide As PowerPoint.Slide

    ' try to address PowerPoint if it's already running
    On Error Resume Next
    Set ppApp = GetObject(, "PowerPoint.Application")
    On Error GoTo 0

    If Not ppApp Is Nothing Then                ' PowerPoint is already running
        Set ppPres = ppApp.ActivePresentation   ' use current presentation
        If ppPres Is Nothing Then               ' if no presentation there
            Set ppPres = ppApp.Presentations.Open("...")    ' open it
        End If
    Else                                        ' new PowerPoint instance necessary
        Set ppApp = New PowerPoint.Application  ' start new instance
        Set ppPres = ppApp.Presentations.Open("...")    ' open presentation
    End If

    ppApp.Visible = True
    ppApp.Activate

    Set ppSlide = ppApp.ActiveWindow.Selection.SlideRange(1)
    Debug.Print ppSlide.SlideID, ppSlide.SlideNumber, ppSlide.SlideIndex
End Sub

我为“ Microsoft PowerPoint x.x对象库”添加了VBA引用,以实现早期绑定和智能感知。

这是后期绑定的替代方法:

Private Sub ControlPowerPointFromExcelLateBinding()
    Dim ppApp As Object
    Dim ppPres As Object
    Dim ppSlide As Object

    On Error Resume Next
    Set ppApp = GetObject(, "PowerPoint.Application")
    On Error GoTo 0

    If Not ppApp Is Nothing Then
        Set ppPres = ppApp.ActivePresentation
        If ppPres Is Nothing Then
            Set ppPres = ppApp.Presentations.Open("...")
        End If
    Else
        Set ppApp = CreateObject("PowerPoint.Application")
        Set ppPres = ppApp.Presentations.Open("...")
    End If

    ppApp.Visible = True
    ppApp.Activate

    Set ppSlide = ppApp.ActiveWindow.Selection.SlideRange(1)
    Debug.Print ppSlide.SlideID, ppSlide.SlideNumber, ppSlide.SlideIndex
End Sub

Here是对早期/晚期绑定差异的解释。如果您要按照注释中的建议通过条件编译来实现这两者,那么我找到了一个解释here

答案 1 :(得分:0)

谢谢你们一千次!!!!真的很感谢帮助!! 使用我绑定到PowerPoint应用程序的变量而不是链接到演示文稿本身的变量为我完成了工作!

这是我现在使用的代码:

Set PowerPoint = CreateObject("Powerpoint.Application")
PowerPoint.Visible = True
PowerPoint.Presentations.Open (pfad & "\Master\Master_Planungsworkshop.pptx")
Set ppApp = GetObject(, "Powerpoint.Application")
Set pppres2 = ppApp.ActivePresentation

input_position = ppApp.ActiveWindow.Selection.SlideRange.SlideIndex