首页 > 解决方案 > VBA 通过选择单元格在列表中打开 PDF

问题描述

我正在制作一张表格,该表格允许用户通过单击单元格来根据不同文件夹中的部分文件名提取 PDF。

我的问题有两个部分。

  1. 我希望文件路径“fp”在所选列的顶部获取活动单元格值。我想这样做是为了便于用户在路径发生变化时使用。
  2. 我已经查找了几种从 excel 打开 PDF 的方法。这些似乎都不起作用,我不确定为什么会这样。
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Activate Macro by click a cell
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A3:B10000")) Is Nothing Then
            Call OpenFile
        End If
    End If
End Sub

Function OpenAnyFile(strPath As String)
    'Put this in as "ActiveWorkbook.FollowHyperlink OpenMe" was not working. Was trying the shell method.
    Set objShell = CreateObject("Shell.Application")
    objShell.Open (strPath)
End Function

Sub OpenFile()
    Dim fp As String, fn As String, TheFile As String

    fp = "R:\Procurement\Invoices\"
    '(((Item 1))) I want it so that fp will return the top value from the top row of this sheet as i would like the path information to be there for easy user modification.
    fn = ActiveCell.Value

    TheFile = Dir(fp & fn & "*.pdf")

    If CBool(Len(fn)) Then
       MsgBox ("File Found")

       '(((Item 2))) Opening the PDf does not work. Below are two ways i have tried to achieve this.
       Call OpenAnyFile(TheFile)
       'ActiveWorkbook.FollowHyperlink TheFile
    End If
End Sub

标签: excelvbashellpdf

解决方案



使用时会出现溢出错误Target.Count。这通常发生在 Ctrl + A 上。如果 Ctrl + A 提供的保护很少,则扩展行为。充其量,您必须按三下才能首先选择区域,然后是使用的范围,然后是整个工作表。在最坏的情况下,需要一次。

来自 MS Docs,re: Range object & Count vs CountLarge properties

https://docs.microsoft.com/en-us/office/vba/api/excel.range.count

CountLarge 属性在功能上与 Count 属性相同,只是如果指定范围的单元格超过 2,147,483,647 个(少于 2,048 列),Count 属性将生成溢出错误。但是,CountLarge 属性可以处理的范围最大为工作表的最大大小,即 17,179,869,184 个单元格。


Shell 函数与 Shell 对象

shell函数超级好用,不需要创建对象的开销。

例如,使用 shell 函数在 Internet Explorer 中打开 myfile.pdf 的第 4 页:

Shell("C:\Program Files\Internet Explorer\iexplore.exe " + "C:\myfile.pdf#Page=4")

注意 `"[...]iexplore.exe [...]" 后面有一个空格,这很重要。

用您选择的应用程序替换可执行文件路径

注意:许多应用程序无法将 PDF 打开到特定页面。简单地省略#Page=它的部分部分是一个问题。

注意:您还可以像这样获取新进程的 PID:

vPID = Shell("C:\Program Files\Internet Explorer\iexplore.exe " + "C:\myfile.pdf#Page=4")

推荐阅读