使用VBA将2个pdf合并为一个

时间:2019-11-20 17:03:50

标签: vba pdf solidworks

我目前正在处理一个宏,该宏可以从SolidWorks文件创建PDF,然后,如果SolidWorks文件是装配体,它将把pdf及其BOM合并。

问题是我已经对宏的合并部分进行了编码,但是我在代码的合并行中始终得到“ False”结果,我找不到原因...

一旦被调试,它将成为一个功能,它将合并2个文件路径。

您能帮我使宏实际合并两个文件吗?我找不到任何有关为什么它可以返回错误结果的信息。

因此,谢谢您的帮助!

这是我的实际代码:

Sub CombinePDFs() '(ByVal NewAsmPdf As String, ByVal OldAsmPdf As String)

' The function will combine the PDFs keeping the BOM of the older file merged (The one which is replaced)

Dim Adobe As AcroPDDoc
Dim PDF1    As Object
Dim PDF2    As Object
Dim PageNF  As Long
Dim PageOF  As Long

Dim b As Byte
Dim NewAsmPdf   As String
Dim OldAsmPdf   As String

NewAsmPdf = "Path.PDF"
OldAsmPdf = "Path_BOM.PDF"

' Defines the two PDFs to be merged
Set PDF1 = CreateObject("AcroExch.PDDoc")
PDF1.Open (NewAsmPdf)
Set PDF2 = CreateObject("AcroExch.PDDoc")
PDF2.Open (OldAsmPdf)

'Get the pages to be keep
PageNF = PDF1.GetNumPages
PageOF = PDF2.GetNumPages - PageNF

'Insert PDF2 BOM in PDF1
If PDF1.InsertPages(PageNF, PDF2, PageNF + 1, PageOF, 0) Then 'Here is my problem : Keep having false (No merge)
Kill (OldAsmPdf)
Else
MsgBox ("Could not merge the Old and New file")
End If

End Sub

已解决!

我发现VBA从0开始计数(因此第1页实际上是第0页),因此由于属性中的值不可能而返回false。

这是我完成的功能的代码:

Function CombinePDFs(ByVal NewAsmPdf As String, ByVal OldAsmPdf As String)


' The function will combine the 2 PDFs and replace the OldFile by the NewFile

    Dim PDF1    As Object
    Dim PDF2    As Object

    Dim PageNF  As Long
    Dim PageOF  As Long

    Dim NewAsmPdf   As String
    Dim OldAsmPdf   As String

    ' Defines the two PDFs to be merged
    Set PDF1 = CreateObject("AcroExch.PDDoc")
    PDF1.Open (NewAsmPdf)
    Set PDF2 = CreateObject("AcroExch.PDDoc")
    PDF2.Open (OldAsmPdf)

    'Get the pages to be keep
    PageNF = PDF1.GetNumPages
    PageOF = PDF2.GetNumPages


    ' Insert PDF2 BOM in PDF1
    If PDF1.InsertPages(PageNF - 1, PDF2, PageNF, PageOF-1, 0)

        If Not PDF1.Save(PDSaveFill, NewAsmPdf) Then
            MsgBox ("Not saved")
        End If

        ' Delete "_BOM.PDF" file
        PDF2.Close
        Kill (OldAsmPdf)

    Else
        MsgBox ("Could not merge the Old and New file")
    End If

    ' Clear memory
    Set PDF1 = Nothing
    Set PDF2 = Nothing

    End Function

玩得开心!

0 个答案:

没有答案