2014-07-08 66 views
2

我正在嘗試創建一個MS Word宏來檢查並查看是否打開了一個特定的PowerPoint文件。如果是,那麼我希望它轉到下一個,但如果沒有,則打開該文件。如何檢查PowerPoint文件是否打開?

Public Sub CommandButton1_Click() 
Dim pptApp As Object 
Dim pptPres As String 
'Dim nSlide As PowerPoint.Presentation 
Dim folderPath, file As String 

folderPath = ActiveDocument.Path & Application.PathSeparator 
file = "Huntington_Template.pptx" 

Set pptApp = CreateObject("PowerPoint.Application") 

If pptApp.presentations(file).Enabled = True Then 
    GoTo cont 
Else 
    pptApp.Visible = True 
    pptApp.presentations.Open (folderPath & file) 
End If 

續:

End Sub 

回答

2

添加到您的模塊(aircode,可能需要調試的幫助):

Function PPTFileIsOpen(pptApp as object, sFullname as string) as boolean 
    Dim x as long 
    For x = 1 to pptApp.Presentations.Count 
    if pptApp.Presentations(x).fullname = sFullname) Then 
     PPTFileIsOpen = True 
     Exit Function 
    end if 
    Next 
End Function 

然後,而不是你的:

If pptApp.presentations(file).Enabled = True Then 

使用:

If Not PPTFileIsOpen(pptApp, folderPath & file) Then 
    ' open the file as you're already doing 
End If 
+0

功能PPTFileIsOpen(pptApp作爲PowerPoint.Application,sFullname作爲字符串)爲布爾 昏暗X只要 對於x = 1至pptApp.Presentations.Count 如果pptApp.Presentations(x)的.FullName = sFullname然後 PPTFileIsOpen =真 退出功能 結束如果 接下來 端功能 我改變了pptApp到PowerPoint.Application – James

+0

我得到一個錯誤代碼91 - 對象變量或帶塊變量未設置 你能在這方面幫助? – James

+0

爲什麼您將其更改爲PowerPoint.Application?除非您在代碼中設置了對PowerPoint的引用,並將主代碼更改爲Dim pptApp作爲PowerPoint.Application,否則它將無法工作。 –

0

我已經使用這個函數來確定工作簿是否已經打開,它可能適用於powerpoint。

Public Function IsWorkBookOpen(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: IsWorkBookOpen = False 
    Case 70: IsWorkBookOpen = True 
    Case Else: Error ErrNo 
    End Select 
End Function 

然後,您可以做這樣的事情

Ret = IsWorkBookOpen("C:\Book1.xlsm") 
If Ret = True Then 
    Set wb = Application.Workbooks("C:\Book1.xlsm") 
    wb.Activate 
Else 
    Set wb = Application.Workbooks.Open("C:\Book1.xlsm") 
End If 
+0

這將決定* some * app是否打開/鎖定文件;該應用程序可能是PowerPoint或其他應用程序(啓用了預覽窗格的Windows資源管理器,例如Dropbox或...)。這是一個好主意,通過結合這兩個建議來檢查這個文件是否在PPT中打開。 –

3

的史蒂夫的代碼中的微小變化調用它,如果你想不只是測試,如果文稿處於打開狀態,也可直接使用它:

Function GetPowerpointFileIfOpen(pptApp As Object, sFullname As String) As Object 
    For Each p In pptApp.Presentations 
     If p.FullName = sFullname Then 
      Set GetPowerpointFileIfOpen = p 
      Exit Function 
     End If 
    Next p 
End Function 

然後你就可以測試是否文稿處於打開狀態 - 或以其他方式將其打開:

Set ppt = GetPowerpointFileIfOpen(pptApp, sFullName) 
If ppt Is Nothing Then 
    Set ppt = pptApp.Presentations.Open(sFullName, False) 
End If