Home » excel » excel – How to save PDF image to XLSX by browsing file?

excel – How to save PDF image to XLSX by browsing file?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Below is what I’ve tried.

My goal is to select the PDF File from the Path by browsing it, not by actually giving the string filepath and to Save as .XLSX also by browsing where to save it.

The code is below:

Option Explicit

Sub PDF_To_Excel()


Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Setting")

Dim pdf_path As Variant
Dim excel_path As String

pdf_path = Application.GetOpenFilename(FileFilter:="PDF Files (*.PDF), *.PDF", Title:="Select File To Be Opened")
excel_path = setting_sh.Range("E12").Value 'should save it as browsing location


Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File

Set fo = fso.GetFolder(pdf_path)

Dim wa As Object
Dim doc As Object
Dim wr As Object

Set wa = CreateObject("word.application")



'Dim wa As New Word.Application
wa.Visible = True
'Dim doc As Word.Document

Dim nwb As Workbook
Dim nsh As Worksheet
'Dim wr As Word.Range


For Each f In fo.Files
    Set doc = wa.documents.Open(f.Path, False, Format:="PDF Files")
    Set wr = doc.Paragraphs(1).Range
    wr.WholeStory


    Set nwb = Workbooks.Add
    Set nsh = nwb.Sheets(1)
    wr.Copy

    nsh.Paste
    nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))

    doc.Close False
    nwb.Close False
Next

wa.Quit

MsgBox "Done"


End Sub

I get the following error:
“Run-time error ’76’: Path not found on the following line:

Set fo = fso.GetFolder(pdf_path)

Any help would be more than appreciated.

Many thanks!

How to&Answers:

According to your comments, you want to select a PDF file and the code will then select all PDFs in that folder. An odd way of doing it, but not difficult. Your code allows for the selection of the file – you just need to select the parent folder of that file.

You can do that with the FSO like so:

'existing code
pdf_path = Application.GetOpenFilename(FileFilter:="PDF Files (*.PDF), *.PDF", Title:="Select File To Be Opened")

'create an object referring to the file chosen
Set objFile = FSO.GetFile(pdf_path)

'Derive the path of the file's parent folder
sPath = Left(objFile.Path, Len(objFile.Path)-Len(objFile.Name))

'existing code but using `sPath` derived above
Set fo = fso.GetFolder(sPath)

You probably ought to check that the user has indeed chosen a file beforehand though, in case they’ve hit Cancel:

If pdf_path = False Then
'stop execution, throw an error.. you choose
End If