Открыть файл pdf vba excel

 

evgeniy_m

Пользователь

Сообщений: 109
Регистрация: 07.07.2014

#1

30.08.2014 14:04:35

Доброе время суток! Идея такая. Есть файл MS Excell. В нем кнопка, по нажатии которой открывается *.pdf файл. Код VBA такой:

Код
Sub PDFOpen()  
    Programm = "c:Program FilesAdobeReader 11.0ReaderAcroRd32.exe"          

    Files = "d:1.pdf"            

    Shell Programm & " " & Files, vbNormalFocus 
End Sub
 

Проблема в следующем… Файл MS Excel запускается локально с разных компьютеров и путь к Adobe Reader у каждого компьютера разный.

Проблема 1: Можно ли переписать код, без указания пути к открытию программы Adobe Reader/Fixed Reader или прочей программы, которая может открыть *.pdf файл?
Проблема 2: Можно ли прописать путь к файлу не «d:1.pdf», а чтобы файл тянул с той же папки где и находиться файл *.pdf?

Заранее спасибо!

 

Игорь

Пользователь

Сообщений: 3632
Регистрация: 23.12.2012

#2

30.08.2014 14:21:41

Неужели сложно поиском воспользоваться… раз десятый на этот вопрос отвечаю

Код
Filename$ = "d:1.pdf"
CreateObject("wscript.shell").Run """" & Filename$ & """" 

указывать путь к программе не требуется, — Windows сама разберется, чем открыть файл

Второй вопрос не понял, — надо искать файл ПДФ с любым именем в той папке, где сохранён файл Excel с макросом?

 

evgeniy_m

Пользователь

Сообщений: 109
Регистрация: 07.07.2014

#3

30.08.2014 14:36:55

Цитата
Игорь пишет: указывать путь к программе не требуется, — Windows сама разберется, чем открыть файл

спасибо большое! Видимо не мог понять как  :(

второй вопрос такой. допустим файл ПДФ находиться с одной папке с файлом ексель. Можно ли не указывать конкретно пусть к ПДФ файлу, а тупо 1.pdf и чтобы его искало в той же папке откуда открыт Ексель файл?

 

Игорь

Пользователь

Сообщений: 3632
Регистрация: 23.12.2012

#4

30.08.2014 15:26:44

Код
Filename$ = ThisWorkbook.path & "1.pdf" 

а если имя файла даже неизвестно, но подразумевается, что в папке будет только один нужный ПДФ файл, — то так:

Код
Filename$ = ThisWorkbook.path & "" & dir(ThisWorkbook.path & "*.pdf") 
 

evgeniy_m

Пользователь

Сообщений: 109
Регистрация: 07.07.2014

Все работает, огромное Вам спасибо!

 

jey

Пользователь

Сообщений: 25
Регистрация: 26.11.2013

Добрый день! Спасибо Игорю за новый для меня способ.
Только я не нашел в описании wscript.shell параметра, отвечающего за открытие определенной страницы пдфки.
Если кто подскажет, буду очень признателен

 

Игорь

Пользователь

Сообщений: 3632
Регистрация: 23.12.2012

такого параметра у wscript.shell нет
он просто запускает файл (аналог двойного щелчка на файле)

думаю, нет простых способов прокрутить до страницы
сложных способов тоже не знаю

 

Лилиенталь

Пользователь

Сообщений: 36
Регистрация: 21.08.2019

Здравствуйте.

Сейчас открывает файл только при полном совпадении имени и расширении.

Как открыть файл, если известно только часть имени и расширение не .pdf, а например .png?

q = Cells(ActiveCell.Row, 1).Value
route = «C:UsersaccountDesktopпечать»
myShell.Run route & q & «.pdf»

p.s. посидел 2 часа в поиске ответа на форуме. Не нашёл.

Изменено: Лилиенталь19.04.2022 19:31:25

 

Jack Famous

Пользователь

Сообщений: 10852
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Лилиенталь, здравствуйте
Прочитайте Приём

Проверка текста по маске

, обратите особенное внимание на спецсимвол подстановки * и примеры его использования — скорее всего, именно он вам и нужен (он и ранее в этой теме появлялся)

Изменено: Jack Famous20.04.2022 09:26:42

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

МатросНаЗебре

Пользователь

Сообщений: 5516
Регистрация: 05.02.2014

#10

20.04.2022 09:47:38

Код
myShell.Run Route & Dir(Route & q & "*.pdf")
 

Лилиенталь

Пользователь

Сообщений: 36
Регистрация: 21.08.2019

Спасибо. Помогло.

Про маски буду читать.

 

Лилиенталь

Пользователь

Сообщений: 36
Регистрация: 21.08.2019

myShell.Run Route & Dir(Route & «*» & q & «*»)

Как оказалось помогло, но не до конца.

Пробел не воспринимает. Файл находит, но не открывает.

ПОМОГИТЕ.

 

Jack Famous

Пользователь

Сообщений: 10852
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

#13

21.04.2022 14:04:50

Цитата
Лилиенталь: Пробел не воспринимает
Цитата
Игорь в ответе #2: Run «»»» & Filename$ & «»»»

попробуйте

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Лилиенталь

Пользователь

Сообщений: 36
Регистрация: 21.08.2019

#14

22.04.2022 09:39:15

Цитата
Jack Famous написал:
попробуйте

Такой вариант даже не видет файл.

Вот мой полный код:

Sub открыть_чертёж()
Dim q As String
Dim Route As String
Dim myShell As Object

On Error Resume Next
Set myShell = CreateObject(«WScript.Shell»)
Cells(ActiveCell.Row, 1).Select

q = Cells(ActiveCell.Row, 1).Value

Route = «C:UsersaccountDesktopКД»

myShell.Run Route & Dir(Route & «»»» & q & «»»»)

‘myShell.Run Route & Dir(Route & «*» & q & «*»)

End Sub

Вариант с «*» открывает любой файл, где в имени файла есть значение ячейки. Но как только в имени появляется пробел, он его видит но не открывает.

Может задачу можно решить другим способом, поэтому поясню принцип задачи.

Есть папка с чертежами. В экселе перечислены все файлы. Задача: в экселе, двойным нажатием на ячейку в котором находиться «КПДМ.741124.447» открывается файл находящийся в папке с именем «Пластина КПДМ.741124.447_под опору.jpg».

Изменено: Лилиенталь22.04.2022 09:41:21

 

МатросНаЗебре

Пользователь

Сообщений: 5516
Регистрация: 05.02.2014

#15

22.04.2022 10:24:14

Код
Sub открыть_чертёж()
    Dim q As String
    Dim Route As String
    Dim myShell As Object
    
    On Error Resume Next
    Set myShell = CreateObject("WScript.Shell")
    Cells(ActiveCell.Row, 1).Select
    
    q = Cells(ActiveCell.Row, 1).Value
    Route =  "C:UsersaccountDesktopКД"
    
    Dim oFile As Object
    For Each oFile In CreateObject("Scripting.FileSystemObject").GetFolder(Route).Files
        If oFile.Name Like "*" & q & "*.pdf" Then
            myShell.Run """" & oFile & """"
            Exit For
        End If
    Next
End Sub
 

МатросНаЗебре

Пользователь

Сообщений: 5516
Регистрация: 05.02.2014

#16

22.04.2022 10:27:52

Цитата
написал:
решить другим способом, поэтому поясню принцип задачи.Есть папка с чертежами. В экселе перечислены все файлы. Задача: в экселе, двойным нажатием на ячейку в котором находиться «КПДМ.741124.447» открывается файл находящийся в папке с именем «Пластина КПДМ.741124.447_под опору.jpg».
Код
'Это в модуль листа
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    открыть_чертёж2 Target
End Sub

Sub открыть_чертёж2(rActiveCell As Range)
    Dim q As String
    Dim Route As String
    Dim myShell As Object
    
    On Error Resume Next
    Set myShell = CreateObject("WScript.Shell")
    
    q = rActiveCell.Value
    Route =  "C:UsersaccountDesktopКД"
    
    Dim oFile As Object
    For Each oFile In CreateObject("Scripting.FileSystemObject").GetFolder(Route).Files
        If oFile.Name Like "*" & q & "*" Then
            myShell.Run """" & oFile & """"
            Exit For
        End If
    Next
End Sub

Изменено: МатросНаЗебре22.04.2022 10:28:06

 

Лилиенталь

Пользователь

Сообщений: 36
Регистрация: 21.08.2019

 

LAV75

Пользователь

Сообщений: 61
Регистрация: 09.01.2017

Не работает код почему-то.
Просто не происходит ничего…
пишет «Argument not optional»

от модератора: можно ж было в одном все написать???

Изменено: БМВ17.08.2022 10:50:25

 

LAV75

Пользователь

Сообщений: 61
Регистрация: 09.01.2017

Справедливо.
Учту.

По событию двойного клика не происходит ничего.

Попытался от события отключить, просто на кнопку сам макрос накинуть, начал писать выше описанную фразу…

Изменено: LAV7517.08.2022 11:04:49

 

_Boroda_

Пользователь

Сообщений: 1496
Регистрация: 27.07.2013

Контакты см. в профиле

#20

17.08.2022 14:25:34

Попробуйте это

Код
Sub открыть_чертёж2(rActiveCell As Range)
    Dim q As String
    Dim Route As String
    Dim myShell As Object

переписать вот так

Код
Sub открыть_чертёж2()
    Dim q As String
    Dim Route As String
    Dim myShell As Object
set rActiveCell=selection(1)

Не проверял

Скажи мне, кудесник, любимец ба’гов…

I’m trying to open all appropriate PDFs found in the same directory as my Excel workbook using VBA. I’ve added the Adobe Acrobat xx.x Type Library reference to the project. But when I try to create the .App object I get a «Run-time error ‘429’:» error.

What am I missing?

Here’s the code;

Sub ImportNames()
Dim BlrInfoFileList() As String, NbrOfFiles As Integer, FileNameStr As String
Dim X As Integer, pdfApp As AcroApp, pdfDoc As AcroAVDoc


'Find all of the Contact Information PDFs
FileNameStr = Dir(ThisWorkbook.Path & "*Contact Information.pdf")
NbrOfFiles = 0
Do Until FileNameStr = ""
    NbrOfFiles = NbrOfFiles + 1
    ReDim Preserve BlrInfoFileList(NbrOfFiles)
    BlrInfoFileList(NbrOfFiles) = FileNameStr
    FileNameStr = Dir()
Loop

For X = 1 To NbrOfFiles
    FileNameStr = ThisWorkbook.Path & "" & BlrInfoFileList(X)
    Set pdfApp = CreateObject("AcroExch.App")
    pdfApp.Hide

    Set pdfDoc = CreateObject("AcroExch.AVDoc")
    pdfDoc.Open FileNameStr, vbNormalFocus

    SendKeys ("^a")
    SendKeys ("^c")
    SendKeys "%{F4}"

    ThisWorkbook.Sheets("Raw Data").Range("A1").Select
    SendKeys ("^v")
    Set pdfApp = Nothing
    Set pdfDoc = Nothing

    'Process Raw Data and Clear the sheet for the next PDF Document
Next X
End Sub

Pᴇʜ's user avatar

Pᴇʜ

56k9 gold badges49 silver badges73 bronze badges

asked Oct 4, 2013 at 15:36

user2668956's user avatar

If it’s a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

answered Oct 4, 2013 at 15:54

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

1

Use Shell "program file path file path you want to open".

Example:

Shell "c:windowssystem32mspaint.exe c:usersadminx.jpg"

Bugs's user avatar

Bugs

4,4919 gold badges32 silver badges41 bronze badges

answered Mar 16, 2014 at 7:48

Cyaramar's user avatar

Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .

Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook

Application.ScreenUpdating = False

Set Basebk = ThisWorkbook

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & ""
mFolder = diaFolder.SelectedItems(1) & ""
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & ""
Filename = Dir(subFldr & "*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
   Workbooks.Open Filename:=subFldr & "" & Filename, ReadOnly:=True
   For Each Sheet In ActiveWorkbook.Sheets
   Set Actbk = ActiveWorkbook
   s = ActiveWorkbook.Name
   HK = Left(s, Len(s) - 4)
   If InStrRev(HK, "_S") <> 0 Then
   HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
   Else
   HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
   End If
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
   ActiveSheet.Name = HK

   ' Open pdf file to copy SIC Decsription
   pathAndFileName = subFlodr & J
   adobeReaderPath = "C:Program Files (x86)AdobeAcrobat Reader DCReaderAcroRd32.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("0:00:2")

    SendKeys "%vpc"
    SendKeys "^a", True
    Application.Wait Now + TimeValue("00:00:2")

    ' send key to copy
     SendKeys "^c"
    ' wait 2 secs
     Application.Wait Now + TimeValue("00:00:2")
      ' activate this workook and paste the data
        ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(HK)
        Range("O1:O5").Select
        ws.Paste

        Application.Wait Now + TimeValue("00:00:3")
        Application.CutCopyMode = False
        Application.Wait Now + TimeValue("00:00:3")
       Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
       ' send key to close pdf file
        SendKeys "^q"
       Application.Wait Now + TimeValue("00:00:3")
 Next Sheet
 Workbooks(Filename).Close SaveAs = True
 Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub

I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement

Regards,
Hema Kasturi

answered Nov 17, 2017 at 17:57

user8959244's user avatar

WOW…
In appreciation, I add a bit of code that I use to find the path to ADOBE

Private Declare Function FindExecutable Lib "shell32.dll" Alias "FindExecutableA" _
    (ByVal lpFile As String, _
     ByVal lpDirectory As String, _
     ByVal lpResult As String) As Long

and call this to find the applicable program name

Public Function GetFileAssociation(ByVal sFilepath As String) As String
Dim i               As Long
Dim E               As String
    GetFileAssociation = "File not found!"
    If Dir(sFilepath) = vbNullString Or sFilepath = vbNullString Then Exit Function
    GetFileAssociation = "No association found!"
    E = String(260, Chr(0))
    i = FindExecutable(sFilepath, vbNullString, E)
    If i > 32 Then GetFileAssociation = Left(E, InStr(E, Chr(0)) - 1)
End Function

Thank you for your code, which isn’t EXACTLY what I wanted, but can be adapted for me.

answered Sep 12, 2018 at 23:48

Ian Hicks's user avatar

1

Here is a simplified version of this script to copy a pdf into a XL file.


Sub CopyOnePDFtoExcel()

    Dim ws As Worksheet
    Dim PDF_path As String

    PDF_path = "C:Users...DocumentsThis-File.pdf"


    'open the pdf file
    ActiveWorkbook.FollowHyperlink PDF_path

    SendKeys "^a", True
    SendKeys "^c"

    Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)

    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Sheets("Sheet1")

    ws.Activate
    ws.Range("A1").ClearContents
    ws.Range("A1").Select
    ws.Paste

    Application.ScreenUpdating = True

End Sub

answered Jul 12, 2019 at 16:13

Keith Swerling's user avatar

I have code below, it seems to not be opening the pdf please help. I am very fluent with VBA but not with vba object orientated code with adobe.

Option Explicit
Option Compare Text

Sub SeperatePDFFile()

Dim selectpdf As String
Dim caption As String
Dim filter As String
Dim gApp As Acrobat.AcroApp
Dim gPDDoc As Acrobat.AcroPDDoc

Set gApp = CreateObject("AcroExch.App")
Set gPDDoc = CreateObject("AcroExch.PDDoc")

caption = "Please Select an input file must extension .pdf"
selectpdf = Application.GetOpenFilename(filter, , caption)

gPDDoc.Open (selectpdf)

End Sub

Chrismas007's user avatar

Chrismas007

6,0654 gold badges23 silver badges47 bronze badges

asked Jan 22, 2015 at 15:03

ColdTeck's user avatar

7

If you only need to open the PDF, is there any reason to automate Acrobat rather thank just using ShellExecute (which’d open pretty much any file that’s registered in windows)?

Option Explicit

    Private Declare 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 Test()

        If LaunchFile("C:tempsomefile.pdf") > 32 Then
            ' it worked, the file's open
        Else
            ' failed for some reason
        End If

    End Sub

    Function LaunchFile(sFileName As String) As Long
    ' Requires the full path to the file to be launched

        LaunchFile = ShellExecute(0&, vbNullString, sFileName, vbNullString, vbNullString, vbNormalFocus)

    End Function

answered Jan 22, 2015 at 15:34

Steve Rindsberg's user avatar

Steve RindsbergSteve Rindsberg

14.2k1 gold badge29 silver badges34 bronze badges

2

0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 8

1

29.12.2013, 21:34. Показов 10799. Ответов 7


Студворк — интернет-сервис помощи студентам

Как из вба, нажатием на кнопку, открыть документ в формате пдф



0



Апострофф

Заблокирован

29.12.2013, 21:36

2

Vangertorn, открыть в чём?



0



0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 8

29.12.2013, 21:40

 [ТС]

3

Апострофф,
в Adobe Reader



0



11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,147

29.12.2013, 21:45

4

Как открыть файл:

Простой способ открыть файл, связанный с каким либо приложением Windows
Автор: Роман Коновалов

Под Windos NT:

Shell «cmd /X /C start c:mydocexample.doc»

Под Windos 9x:

Shell «start c:mydocexample.doc»

При способе, предложенном Автором появляется минимизированое окно Command Prompt.
Не всем юзерам это нравиться. Как альтернативу можно использовать
API функцию ShellExecute. Для этого необходимо испльзовать декларацию:

‘ Декларация функции для запуска файла.
Public Declare 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

‘ Декларация константы для максимизирования окна открываемого приложения.
‘ Для работы с другими константами смотрите MSDN.
Public Const SW_SHOWMAXIMIZED = 3

‘После этого нижеследующий код будет открывать файл test.xls.

Call ShellExecute(0, «open», «test.xls»,»», «», SW_SHOWMAXIMIZED)



3



0 / 0 / 0

Регистрация: 02.12.2013

Сообщений: 8

29.12.2013, 22:04

 [ТС]

5

Alex77755, первые 2 способа попробовал — не работают, при использовании функции — Public Const SW_SHOWMAXIMIZED = 3, эта строка выделяется красным(



0



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

29.12.2013, 22:40

6

Visual Basic
1
2
3
Sub ttt()
CreateObject("WScript.Shell").Run """C:Program FilesAdobeReader 8.0ReaderAcroRd32.exe"" /n/t ""C:TempIMG_0001.pdf"""
End Sub

Упс, /t лишнее — это для печати
Ну пусть будет пример и для печати…



3



Модератор

Эксперт функциональных языков программированияЭксперт Python

34709 / 19230 / 4040

Регистрация: 12.02.2012

Сообщений: 32,197

Записей в блоге: 13

30.12.2013, 13:43

7

Цитата
Сообщение от Vangertorn
Посмотреть сообщение

Public Const SW_SHOWMAXIMIZED = 3, эта строка выделяется красным(

— а подумать? Может, в этом контексте Public-описания недопустимы? Ты же, небось, вставил этот код в лист или в форму?



1



0 / 0 / 0

Регистрация: 24.08.2018

Сообщений: 1

04.10.2018, 17:54

8

Цитата
Сообщение от Alex77755
Посмотреть сообщение

Call ShellExecute(0, «open», «test.xls»,»», «», SW_SHOWMAXIMIZED)

На мой взгляд, использование штатных функций ОС, прописанных в системных библиотеках, по прямому назначению является наилучшим вариантом, в любом случае. Хотя могу и ошибаться…



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.10.2018, 17:54

8

VBA Macro To Open A PDF File

The previous week, while I was preparing a presentation, I encountered the following problem: how could I open a PDF file from a PowerPoint presentation? And more precisely, how could I open a PDF file to a particular page (i.e., 46) and view that page with a specific view (i.e., fit page)? I managed to solve this problem by using VBA. The challenging part was to use the PDF objects from VBA, so I searched for Adobe SDK to find the “vocabulary” that uses Adobe in their programs (Acrobat Reader/Pro). I ended up with a VBA macro that can be utilized from any office application (Word, PowerPoint & Excel) since it is free from application-specific objects (i.e., sheets). Note that you should have installed Adobe Acrobat Professional on your computer to use this macro.  

Update

Update 19/9/2012: However, there is a way to open a PDF from an Office application even with Adobe Reader.

Update 30/4/2013: A more generic VBA code that works with both Adobe Reader and Professional can be found here.

VBA code

Option Explicit
Option Private Module

Sub OpenPDFPageView()
    
    'By Christos Samaras
    'https://myengineeringworld.net
    
    'In order to use the macro you must enable the Acrobat library from VBA editor:
    'Go to Tools -> References -> Adobe Acrobat xx.0 Type Library, where xx depends
    'on your Acrobat Professional version (i.e. 9.0 or 10.0) you have installed to your PC.
    
    'Alternatively you can find it Tools -> References -> Browse and check for the path
    'C:Program FilesAdobeAcrobat xx.0Acrobatacrobat.tlb
    'where xx is your Acrobat version (i.e. 9.0 or 10.0 etc.). 
    
    Dim PDFApp As AcroApp
    Dim PDFDoc As AcroAVDoc
    Dim PDFPageView As AcroAvPageView
    Dim PDFPath As String
    Dim DisplayPage As Integer
    
    'Change this to your own complete PDF path
    'Full path example
    'PDFPath = "C:Program FilesAutodeskACADM 2010Setupen-USSetupResDocsAcad_Mech_2010_UserGuide.pdf"
    'For Word
    'PDFPath = ThisDocument.Path & "" & "PDF Sample.pdf"
    'For Power Point
    'PDFPath = ActivePresentation.Path & "" & "PDF Sample.pdf"
    'For Excel
    PDFPath = ThisWorkbook.Path & "" & "PDF Sample.pdf"
    
    'Set the page you want to be displayed
    DisplayPage = 3
    
    'Initialize Acrobat by creating App object
    Set PDFApp = CreateObject("AcroExch.App")
    
    'Set AVDoc object
    Set PDFDoc = CreateObject("AcroExch.AVDoc")
    
    'Open the PDF
    If PDFDoc.Open(PDFPath, "") = True Then
        PDFDoc.BringToFront
        
        'Maximize the document
        Call PDFDoc.Maximize(True)
        
        Set PDFPageView = PDFDoc.GetAVPageView()
        
        'Go to the desired page
        'The first page is 0
        Call PDFPageView.GoTo(DisplayPage - 1)
        
        '-------------
        'ZOOM options
        '-------------
        '0 = AVZoomNoVary
        '1 = AVZoomFitPage
        '2 = AVZoomFitWidth
        '3 = AVZoomFitHeight
        '4 = AVZoomFitVisibleWidth
        '5 = AVZoomPreferred
        
        'Set the page view of the pdf
        Call PDFPageView.ZoomTo(2, 50)
    
    End If

    Set PDFApp = Nothing
    Set PDFDoc = Nothing
    
    On Error Resume Next
    
    'Show the adobe application
    PDFApp.Show
    
    'Set the focus to adobe acrobat pro
    AppActivate "Adobe Acrobat Pro"
        
End Sub 

Update 19/9/2012: VBA code for Adobe Reader

I received some e-mails from people asking me if it is possible to open a PDF file using Adobe Reader. Well, it is possible, but the “Sendkeys” method must be employed. See the VBA function below. Keep in mind that this function also works with Adobe Professional.

Option Explicit

Function OpenPDFPage(PDFPath As String, PageNumber As Long, PageView As Integer)
    
    'Opens a pdf file, at specific page and with specific view.
    'Sendkeys method is used for simulating keyboard shortcuts.
    'It can be used with both Adobe Reader & Adobe Professional.
    
    'By Christos Samaras
    
    'This line depends on the apllication you are using.
    'For Word
    'ThisDocument.FollowHyperlink PDFPath, NewWindow:=True
    'For Power Point
    'ActivePresentation.FollowHyperlink PDFPath, NewWindow:=True
    'For Excel
    ThisWorkbook.FollowHyperlink PDFPath, NewWindow:=True
    SendKeys ("^+N" & PageNumber & "~^" & PageView), True

End Function

Sub Test()

    OpenPDFPage "C:Test.pdf", 115, 2
    
    'Page view options:
    '0: Full Page
    '1: Zoom to 100%
    '2: Page Width

End Sub

Although the above function works, the “sendkeys” method has a severe shortcoming: when the macro runs, the user must not use the keyboard because it is possible to corrupt the function. To sum up, if you have Adobe Professional installed on your computer, use the first macro. In case you have Adobe Reader, use the function.

Update 22/3/2013: Fix the function bug in Adobe Reader

It seems that the last update of the Adobe Reader (and Professional) has changed one important setting, and since then, the function doesn’t work. I am referring to the “Restore last view settings when reopening documents.” As Jean-Sébastien wrote in the comments, the macro acts strangely. However,  the workaround for this problem is quite easy.  

1) Go to Edit –> Preferences in your Adobe PDF Reader.

Adobe Preferences

2) Choose the Document tab and uncheck the option: “Restore last view setting when reopening documents.”

Adobe Last Page Viewed

3) Press, OK, and that’s it! The function will work again.

Update 30/4/2013: A better approach

A more generic VBA code that works with both Adobe Reader and Professional can be found here. It doesn’t require reference to the Adobe Type Library!

Sample files

The RAR file contains the following files:

  1.  A VBA module with the above code for Adobe Professional. You can import it into any office application you want.
  2. A Word document, a PowerPoint presentation, and an Excel workbook are used to demonstrate the same VBA code usage in different applications (see the video above).
  3.  A short PDF file is opened by the above macro (for Adobe Professional).
  4.  Update 19/9/2012: a VBA module with the function for Adobe Reader (and Adobe Professional).

Download it from here

These files can be opened with Office 2007 or newer. Please, remember to enable macros before using them.

Read also

Open PDF File With VBA
Export Excel Charts As TIFF images Using Adobe Professional
VBA Macro To Convert PDF Files Into Different Format

Page last modified: July 25, 2021

Author Image

Hi, I am Christos, a Mechanical Engineer by profession (Ph.D.) and a Software Developer by obsession (10+ years of experience)! I founded this site back in 2011 intending to provide solutions to various engineering and programming problems.

Add Content Block

Понравилась статья? Поделить с друзьями:
  • Открыть файл microsoft word 2007
  • Открыть файл excel через командную строку
  • Открыть файл excel с помощью vba
  • Открыть файл excel с паролем онлайн
  • Открыть файл excel во весь экран