1

I have an Excel spreadsheet. One of the columns in the spreadsheet contains the name of a pdf file; page number (name of file;5).

How do I write a VBA function so that when the user clicks in any of the cells in that column, the name of the file and the page number are passed as variables and the pdf file opens to the page specified?

1 Answer 1

5

To achieve this:

  1. Create an event handler for the worksheet's SelectionChanged event.
  2. Create a parsing function for the cell's value.
  3. Create a subroutine that launches Acrobat with the page number parameter.

See the following sample code. The constants should be changed according to your system. This code needs to be pasted in the worksheet's VBA macros editor.

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
2
  • I pasted this code into the Worksheet VBA macros editor. The necessary information is in column 3 (m:\hyperlink\test.pdf;5). I click on the cell in column 3 that contains this information and the document did not open. Nothing happened. What step am I missing to this process in order to get this to work. Thank you!
    – user299302
    Mar 23, 2010 at 10:18
  • Make sure you change MyPathColumn to 3, and that PathToAcrobatExe points to the path where Adobe Acrobat Reader's main exe file is placed (it may be called Acrord32.exe, Acrobat.exe, etc.)
    – M.A. Hanin
    Mar 23, 2010 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.