excel - 存在文件的超链接

标签 excel vba excel-formula

我正在尝试查看一个 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/

相关文章:

excel - 如何将格式和公式从 Excel 范围复制到另一个范围?

php - 在 PHPSpreadsheet 中迭代时如何获取单元格坐标?

excel - 填充列中的可见单元格

更改单元格后,Excel复制值与对应于键的VBA

excel - 如何使用 Worksheet_Change 函数找到的表中的值自动填充电子邮件正文

vba - 散点图绘制excel VBA - 不会绘制我的数据范围

vba - 使用 VBA 控制 VBScript

excel - Excel 中的字符计数

excel - 在一系列具有相似公式的单元格中,如何使某些值变为绝对值而某些值保持变量?

excel - 结合 IF 函数和 OR 函数以允许多个条件