如何在Excel VBA中通过相对路径打开PDF文件?
解决Excel VBA中用相对路径打开同目录PDF的问题
我懂你遇到的困扰——绝对路径能正常跑,但换成ThisWorkbook.Path就失效,大概率是路径拼接时没处理好分隔符,或是没考虑工作簿未保存的情况。下面给你两种可靠的解决方案:
方法1:改进版FollowHyperlink(最直接)
之前的代码失败,很可能是直接把ThisWorkbook.Path和文件名拼接时没加路径分隔符(比如路径末尾没有\,拼完就变成C:\xxx\totalscopy.pdf,系统自然找不到文件)。这里我们用Application.PathSeparator自动适配系统分隔符,同时增加文件存在性和工作簿保存状态的检查:
Sub OpeningPDF_RelativePath() Dim pdfFullPath As String Dim currentWorkbookPath As String ' 获取当前Excel文件的所在路径 currentWorkbookPath = ThisWorkbook.Path ' 先判断工作簿是否已保存(未保存的话Path为空) If currentWorkbookPath = "" Then MsgBox "请先保存当前Excel文件,才能使用相对路径打开PDF!", vbExclamation Exit Sub End If ' 拼接PDF的完整路径:路径 + 分隔符 + 文件名 pdfFullPath = currentWorkbookPath & Application.PathSeparator & "copy.pdf" ' 检查目标PDF是否存在,避免报错 If Dir(pdfFullPath) = "" Then MsgBox "找不到指定的PDF文件:" & pdfFullPath, vbCritical Exit Sub End If ' 打开PDF ThisWorkbook.FollowHyperlink pdfFullPath End Sub
方法2:用Windows API(ShellExecute,兼容性更强)
如果FollowHyperlink偶尔出现默认阅读器调用问题,可以试试更底层的ShellExecute方法,它直接调用系统默认程序打开文件:
' 先声明Windows API函数(注意:64位Excel要加PtrSafe) Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _ (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _ ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Sub OpenPDF_WithShellExecute() Dim pdfFullPath As String Dim currentWorkbookPath As String currentWorkbookPath = ThisWorkbook.Path If currentWorkbookPath = "" Then MsgBox "请先保存Excel文件!", vbExclamation Exit Sub End If pdfFullPath = currentWorkbookPath & Application.PathSeparator & "copy.pdf" If Dir(pdfFullPath) = "" Then MsgBox "PDF文件不存在:" & pdfFullPath, vbCritical Exit Sub End If ' 1表示正常窗口打开PDF,其他参数留空即可 ShellExecute 0, "open", pdfFullPath, vbNullString, vbNullString, 1 End Sub
关键注意点:
- 必须确保Excel文件已经保存过,否则
ThisWorkbook.Path会返回空字符串,相对路径就无从谈起。 - 用
Application.PathSeparator代替硬编码的\,能避免路径末尾已有分隔符时出现重复(比如路径是C:\xxx\,拼完不会变成C:\xxx\\copy.pdf)。
内容的提问来源于stack exchange,提问作者ClydeHopper
相关产品推荐
相关产品推荐

