I have code which currently loops through one folder, finds two matching pdf-filenames and merges them into 1 pdf-file always in the same order. File 1 then File 2. My code is slow, maybe because merging PDF files takes a long time, but also because it has to search one folder and match filenames. Before I searched through two folders, but that took too long. I do not want to write the filenames to an Excel-file and then match, but I want to merge the PDF files immediately when VBA finds a match. I found some code and adjusted it to my needs and put some new things into it.
I have seen a lot of code using Acrobat or Pdftk, but I do not have Acrobat and Pdftk does not work with me even though I do exactly what is written on several sites. For some reason Pdftk does not merge my files.
My code matches filenames based on the first part of the filename, before the AnotherWord 2014.pdf or before SomeWord.pdf.
- Example document name1: John Doe SomeWord.pdf
- Example document name2: John Doe AnotherWord 2014.pdf
Please look at this code and please post code which will do the same thing, only much faster. My code isn't the best, but it works. I use PDF reDirect Pro v2.5.2 (freeware) and a reference to the program.
Sub MergePDF_Files() 'Only works with PDF reDirect Pro v2.5.2 'And needs to have a reference to PDF_reDirect_v2500 and PDF reDirect Pro Remote Control Dim fs As Object Dim fld As Object Dim fld2 As Object Dim objFile As Object Dim objFile2 As Object Set fs = CreateObject("Scripting.FileSystemObject") Dim oPDF As New PDF_reDirect_v25002.Batch_RC_AXD Dim TempBool As Boolean Dim Files_to_Merge(1) As String Dim ObjFileName() As String Dim CellNameValue() As String Dim ofn As String Dim cnv As String Dim i As Integer Set fld = fs.GetFolder("C:\MyFolder\PDF Merge\Merging Area") Set fld2 = fs.GetFolder("C:\MyFolder\PDF Merge\Merging Area\Merged") i = 1 For Each objFile In fld.files For Each objFile2 In fld.files CellNameValue() = Split(objFile.Name, " SomeWord.pdf") cnv = CellNameValue(0) ObjFileName() = Split(objFile2.Name, " AnotherWord 2014.pdf") ofn = ObjFileName(0) Files_to_Merge(1) = fld & "\" & ofn & " AnotherWord 2014.pdf" Files_to_Merge(0) = fld & "\" & cnv & " SomeWord.pdf" If StrComp(ofn, cnv) = 0 Then With oPDF TempBool = .Utility_Merge_PDF_Files(fld2 & "\" & ofn & " AnotherWord 2014.pdf", Files_to_Merge) 'The file merges here unless it generates an error and goes to If Not TempBool Then... If Not TempBool Then 'MsgBox "An Error Occured: etc. Else 'Optional End If End With End If i = i + 1 Next objFile2 i = i + 1 Next objFile Set oPDF = Nothing End Sub