使用FollowHyperlink打开后关闭已打开的PDF

时间:2015-01-10 19:18:05

标签: excel vba excel-vba

我正在使用FollowHyperlink方法打开pdf文件,如下所示:

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub

找到了at this thread

我的问题是,如何关闭pdf?

1 个答案:

答案 0 :(得分:1)

以下是我使用的两个选项。

选项1:此选项我用它来杀死所有开放的互联网浏览器,当它们不可见时(又名我搞砸了)。可能有一种方法可以通过这种方式单独输出文件,但我不完全确定没有像@Jeeped提到的API调用那样。我将列出第二个API调用。

找出您正在运行的Adobe类型。打开Windows任务管理器>使用描述Adobe Reader处理并查找.exe。

Sub Kill_All_PDFs()

   '***ErrorHandler***
   On Error Resume Next

   '***Define Variables***
    Dim objectWMI As Object
    Dim objectProcess As Object
    Dim objectProcesses As Object

    '***Set Objects***
    Set objectWMI = GetObject("winmgmts://.")
    Set objectProcesses = objectWMI.ExecQuery( _
        "SELECT * FROM Win32_Process WHERE Name = 'AcroRd32.exe'") '< Change if you need be

    '***Terminate all Open PDFs***
    For Each objectProcess In objectProcesses
        Call objectProcess.Terminate
    Next

    '***Clean Up***
    Set objectProcesses = Nothing
    Set objectWMI = Nothing
End Sub

Option2 API调用方法:

在这里,您可以按标题找到您的PDF文件。我修改了代码以找到Adobe,但如果您想进一步阅读它的工作原理,请在下面列出源代码。只需添加PDF文件顶部显示的标题即可。

来源:http://support.microsoft.com/kb/168204

 Private Declare Function FindWindow _
   Lib "user32" Alias "FindWindowA" _
   (ByVal lpClassName As String, _
   ByVal lpWindowName As String) _
   As Long

   Private Declare Function SendMessage _
   Lib "user32" Alias "SendMessageA" _
   (ByVal hwnd As Long, _
   ByVal wMsg As Long, _
   ByVal wParam As Long, _
   lParam As Long) _
   As Long

  Private Sub Close_AdobeReader()
     Dim lpClassName As String
     Dim lpCaption As String
     Dim Handle As Long

     Const NILL = 0&
     Const WM_SYSCOMMAND = &H112
     Const SC_CLOSE = &HF060&

     lpClassName = "AcrobatSDIWindow"
     lpCaption = "e.g.name - Adobe Reader"  '< add Title Here 

  '* Determine the handle to the Calculator window.
     Handle = FindWindow(lpClassName$, lpCaption$)

  '* Post a message to Calc to end its existence.
     Handle = SendMessage(Handle, WM_SYSCOMMAND, SC_CLOSE, NILL)

  End Sub

希望这能帮到你的路!