我有一个Excel电子表格。电子表格中的一列包含pdf文件的名称;页码(name of file;5
)。
如何编写VBA函数,以便当用户单击该列中的任何单元格时,文件名和页码将作为变量传递,pdf文件将打开到指定的页面?
答案 0 :(得分:5)
实现这一目标:
请参阅以下示例代码。应根据您的系统更改常量。此代码需要粘贴在工作表的VBA宏编辑器中。
Private Const MyPathColumn As Integer = 3
Private Const PathToAcrobatExe As String = _
"C:\Program Files\Adobe\Reader 8.0\Reader\Acrord32.exe"
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error GoTo errHnd
If Target.Cells.Count = 1 Then
If Target.Column = MyPathColumn Then
If Len(Target.text) > 0 Then
Dim filePath As String
Dim pageNumber As Integer
Call ParsePath(Target.text, filePath, pageNumber)
Call RunPdf(filePath, pageNumber)
End If
End If
End If
Exit Sub
errHnd:
Call MsgBox("Error Opening File", vbCritical)
End Sub
Private Function getShellCommand(filePath As String, _
pageNumber As Integer) As String
getShellCommand = PathToAcrobatExe & " /A ""page=" _
& CStr(pageNumber) & """ """ _
& filePath & """"
End Function
Private Sub RunPdf(filePath As String, pageNumber As Integer)
Call Shell(getShellCommand(filePath, pageNumber), _
vbMaximizedFocus)
End Sub
Private Sub ParsePath(text As String, ByRef filePath As String, _
ByRef pageNumber As Integer)
Dim parts() As String
parts = Split(text, ";")
filePath = parts(0)
pageNumber = CInt(parts(1))
End Sub