我正在尝试查看一个 pdf 文档,其中包含文本框中的文件名和用于查看此文件的按钮。
当 pdf 文件位于它打开的路径中时。
当它不存在时,当我单击按钮时,什么也不会发生。
我需要添加一个消息框,以便在找不到 pdf 文件时弹出。
我添加了文件存在功能。我不知道这是否是正确的方法,或者如果文件不存在,是否有更简单的方法将消息框添加到超链接。
我的代码的问题是:
如果该文件存在,它会正常打开,但显示消息框“未找到文档。”
如果该文件不存在,则会显示消息框“未找到文档”。也是如此。
Sub viewdoc()
On Error Resume Next
Dim mypath As String
Dim filename As String
filename = frmDELEGATION.txtLedger.Value
mypath = "E:\4-2022\" & filename & ".pdf"
ThisWorkbook.FollowHyperlink mypath
If Not FileExists(mypath, filename) Then
MsgBox "No Documents Found ."
Exit Sub
End If
End Sub
Function FileExists(ByVal mypath As String, ByVal filename As String) As Boolean
FileExists = (Dir(mypath & filename & ".pdf") <> "")
End Function
最佳答案
查看文档
Option Explicit
Sub ViewDoc1() ' improve e.g. 'ViewLedger'!
ViewDocument "E:\4-2022", frmDELEGATION.txtLedger.Value
End Sub
Sub ViewDocument( _
ByVal FolderPath As String, _
ByVal FileBaseName As String, _
Optional ByVal FileExtension As String = ".pdf")
Const PROC_TITLE As String = "View Document"
If Right(FolderPath, 1) <> Application.PathSeparator Then
FolderPath = FolderPath & Application.PathSeparator
End If
If Len(Dir(FolderPath, vbDirectory)) = 0 Then
MsgBox "The path """ & FolderPath & """ doesn't exist.", _
vbCritical, PROC_TITLE
Exit Sub
End If
If Left(FileExtension, 1) <> "." Then
FileExtension = "." & FileExtension
End If
Dim fName As String: fName = FileBaseName & FileExtension
Dim fPath As String: fPath = FolderPath & fName
If Len(Dir(fPath)) = 0 Then
MsgBox "The file """ & fName & """ was not found in the folder """ _
& FolderPath & """.", vbCritical, PROC_TITLE
Exit Sub
End If
On Error Resume Next
ThisWorkbook.FollowHyperlink fPath
On Error GoTo 0
End Sub
关于excel - 存在文件的超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76302383/