在已打开时设置 PowerPoint 演示文稿(来自 Excel)

Set PowerPoint presentation when already opened (From Excel)

我正在尝试打开由 Excel 中的用户决定的特定 powerpoint 幻灯片。打开Powerpoint到具体幻灯片的代码如下(targ是一个类似"Slide:12"的字符串):

Function rcFollowSlide(targ As String)
    Dim PptPath As String
    Dim pptApp As PowerPoint.Application
    Dim pptPres As PowerPoint.Presentation

    targ = Mid(targ, InStr(targ, ":") + 1)
    targ = Left(targ, Len(targ) - 1)
    PptPath = wsSettings.Range("PPTPath").Value

    If IsPPTOpen(PptPath) Then
        MsgBox "Already opened"
        Exit Function
        'Set ppres =
    Else
        Set pptApp = CreateObject("Powerpoint.Application")
        Set pptPres = pptApp.Presentations.Open(PptPath)
    End If

    If targ > 0 And targ <= pptPres.Slides.Count Then
        pptPres.Slides(CInt(targ)).Select
    Else
        MsgBox "Image " & targ & " N/A."
    End If
End Function

当演示文稿关闭并且必须打开它时,它工作得很好。我还想在 Powerpoint 演示文稿已经打开时将其设置为 pptPres,这样我就可以让代码继续 运行 而无需打开该演示文稿的新实例。我如何首先访问该应用程序并设置演示文稿?

供参考,这里是用来检查PPT是否已经打开的函数

Function IsPPTOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsPPTOpen = False
    Case 70:   IsPPTOpen = True
    Case Else: Error ErrNo
    End Select
End Function

我认为应该这样做:

If IsPPTOpen(PptPath) Then
    Set pptPres = pptApp.Presentations(Dir(PptPath))
    'Set ppres =
    Exit Function
Else

如果您需要激活演示文稿,请尝试:

VBA.AppActivate (Dir(PptPath))    

正如您所指出的,这在某些情况下也可能有效(请参阅下面的 Thierry 评论)。

PPTApp.Activate
PPTPres.Activate

我使用的代码略有不同:

ppProgramPowerPoint.Application

ppPresPowerPoint.Presentation

ppFullPath 是完整路径(路径和文件名)

ppName 是请求的演示文稿的"clean" 名称

' more than 1 Presentstion open
If ppProgram.Presentations.Count > 0 Then
    ppName = Mid(ppFullPath, InStrRev(ppFullPath, "\") + 1, Len(ppFullPath))
    i = 1
    Do Until i = ppProgram.Presentations.Count + 1
        If ppProgram.Presentations.Item(i).Name = ppName Then
            Set ppPres = ppProgram.Presentations.Item(i)
            GoTo OnePager_Pres_Found
        Else
            i = i + 1
        End If
    Loop
End If

OnePager_Pres_Found:
ppPres.Windows(1).Activate  ' activate the Presentation in case you have several open