Hello Rerock,
This macro will search all open PDF documents. If the given document is found then it is closed.
The document name matching is not case sensitive. You may use either the full document name or part of the name to match an open document.
Copy this code into a VBA Module in your workbook.
Macor Code to Close an Opened PDF File
' Written: October 08, 2014
' Author: Leith Ross
' Summary: Searches all open PDF documents. If a document is found that matches the
' given file name either fully or partially, it will be closed. If the given
' file name is not found to be open then a dialog message alerts the user.
' 32 Bit Windows API calls.
Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal aint As Long) As Long
Private Declare Function GetWindow Lib "user32.dll" (ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetClassName Lib "user32.dll" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Sub ClosePDF(ByVal FileName As String)
Dim Found As Boolean
Dim hWnd As Long
Dim Pid As Long
Dim RefCell As Range
Dim ret As Long
Dim Title As String
Dim Tid As Long
Dim WndCls As String
Const GW_HWNDNEXT As Long = 2
Const WM_CLOSE As Long = 16
If FileName = "" Then Exit Sub
hWnd = FindWindow(vbNullString, vbNullString)
Do Until hWnd = 0
WndCls = String(512, Chr(0))
ret = GetClassName(hWnd, WndCls, 512)
If Left(WndCls, ret) = "AcrobatSDIWindow" Then
Title = String(512, Chr(0))
ret = GetWindowText(hWnd, Title, Len(Title))
If InStr(1, Title, FileName, vbTextCompare) Then
ret = SendMessage(hWnd, WM_CLOSE, 0, ByVal 0)
Found = True
Exit Do
End If
End If
hWnd = GetWindow(hWnd, GW_HWNDNEXT)
Loop
If Not Found Then MsgBox "The Following PDF Document Was Not Found :" & vbCrLf & vbCrLf & FileName
End Sub
Example of Using the Macro
Sub CloseTest()
ClosePDF "Signed Agreement"
End Sub
Bookmarks