这应该可以满足您的需求。您需要将 PDF 放在受信任的位置,否则每次尝试打开 PDF 时都会弹出一个窗口。除了受信任的位置之外,可能还有一种解决方法,但我不知道(并且通常不建议使用此类东西)。
您还需要将Hwnd = FindWindow(vbNullString, filename & " - Foxit Reader") 更改为您正在使用的任何 PDF 阅读器,我有 Foxit,所以它现在就是这样。
感谢 Siddharth Rout 提供closing of the PDF。
Option Explicit
'Thanks to Siddharth Rout for this chunk
#If VBA7 Then
Private Declare PtrSafe Function PostMessage Lib "user32" Alias "PostMessageA" _
(ByVal Hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Any) As Long
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassname As String, ByVal lpWindowName As String) As Long
#Else
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" _
(ByVal Hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Any) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassname As String, ByVal lpWindowName As String) As Long
#End If
Private Const WM_CLOSE = &H10
Sub t()
Dim Tcell As Range
Dim link As String
Dim lastrow As Long
Dim iter As Long
With Sheet4
lastrow = .Cells(.Rows.Count, 5).End(xlUp).Row
For iter = 2 To lastrow
Set Tcell = .Cells(iter, 5)
On Error GoTo errhandler
ThisWorkbook.FollowHyperlink Tcell.value
On Error GoTo 0
'Thanks to Siddharth Rout for this chunk
Dim Hwnd As Long
Dim filename As String
filename = Split(Tcell.value, "\")(UBound(Split(Tcell.value, "\")))
'~~> Find the window of the pdf file
Hwnd = FindWindow(vbNullString, filename & " - Foxit Reader")
'~~> Close the file
PostMessage Hwnd, WM_CLOSE, 0, ByVal 0&
continueiter:
Next iter
End With
Exit Sub
errhandler:
Select Case Err.Number
Case -2147221014
Tcell.Interior.Color = vbRed
GoTo continueiter
Case Else
MsgBox "Unhandled Error: " & Err.Number & chr(10) & Err.Description
End Select
End Sub