excel - VBA 通过选择单元格在列表中打开 PDF
问题描述
我正在制作一张表格,该表格允许用户通过单击单元格来根据不同文件夹中的部分文件名提取 PDF。
我的问题有两个部分。
- 我希望文件路径“fp”在所选列的顶部获取活动单元格值。我想这样做是为了便于用户在路径发生变化时使用。
- 我已经查找了几种从 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
解决方案
- 您使用空格的方式非常令人困惑,并且很难理解您的程序。
- 您的代码不会按照编写的方式编译。
- 如果您不返回值 ,为什么要使用 a
Function
而不是a ?Sub
- 如果用户按 Ctrl A 选择整个工作表,您将收到溢出错误。
- 阅读有关 shell 函数的信息 https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/shell-function
使用时会出现溢出错误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")
推荐阅读
- java - Java 8 如何使用 lambda 表达式简化 for 循环
- python - 找不到棋盘角
- javascript - 如何遍历 request.body 并相应地更新对象
- python - 使用 Python 的 CURL 响应中的数据值
- wordpress - WordPress 页面模板超链接
- php - 使用未同步到前端的 Woocommerce 方法保存产品属性
- spring - 休眠:无法通过 UUID 找到
- python - 将 .pem 证书添加到烧瓶(开发服务器)
- python - 如何在 Django 中更改代理模型上字段的最大长度
- javascript - 添加带有自定义文本的单选按钮